teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

追伸追加

2016/10/31 08:31

投稿

退会済みユーザー
answer CHANGED
@@ -12,4 +12,75 @@
12
12
 
13
13
  GridView のデータソースに SqlDataSource などのデータソースコントロールを使ってないそうですが、使わない理由があるのでしょうか?
14
14
 
15
- データソースコントロールを使うことで、データバインドするタイミングとかその他いろいろなことを自動的に行ってくれますので、特に理由がない限り使うべきなのですが。
15
+ データソースコントロールを使うことで、データバインドするタイミングとかその他いろいろなことを自動的に行ってくれますので、特に理由がない限り使うべきなのですが。
16
+
17
+ 【2016/10/31 17:30 追伸】
18
+
19
+ ページ B は、私の上の回答で述べたように、以下のようにデータソースコントロールを利用して作れば、データバインドのタイミングとかに一切悩む必要はなく、Page_Load 内のコード以外は一行も自力で書く必要もなく、簡単に作れると思います。検討してみてください。
20
+
21
+ (注:コードの中の Customers, Orders テーブルは Microsoft が提供する Northwind サンプルデータベースのものです)
22
+
23
+ ```
24
+ <script runat="server">
25
+
26
+ // 2016/10/31 teratail の検証用
27
+ // https://teratail.com/questions/53395
28
+
29
+ protected void Page_Load(object sender, EventArgs e)
30
+ {
31
+ if (!Page.IsPostBack)
32
+ {
33
+ //int selectedIndex = (int)Session["Index"]; の代わりに直接設定
34
+ int selectedIndex = 5;
35
+
36
+ DropDownList1.SelectedIndex = selectedIndex;
37
+ }
38
+ }
39
+ </script>
40
+
41
+ <html xmlns="http://www.w3.org/1999/xhtml">
42
+ <head runat="server">
43
+ <title></title>
44
+ </head>
45
+ <body>
46
+ <form id="form1" runat="server">
47
+
48
+ <asp:SqlDataSource ID="SqlDataSource1" runat="server"
49
+ ConnectionString="<%$ ConnectionStrings:NORTHWINDConnectionString %>"
50
+ SelectCommand="SELECT [CustomerID], [CompanyName] FROM [Customers]">
51
+ </asp:SqlDataSource>
52
+ <asp:DropDownList ID="DropDownList1" runat="server"
53
+ DataSourceID="SqlDataSource1" DataTextField="CompanyName"
54
+ DataValueField="CustomerID" AutoPostBack="True">
55
+ </asp:DropDownList>
56
+
57
+ <asp:SqlDataSource ID="SqlDataSource2" runat="server"
58
+ ConnectionString="<%$ ConnectionStrings:NORTHWINDConnectionString %>"
59
+ SelectCommand="SELECT [OrderID], [CustomerID], [ShippedDate], [Freight], [EmployeeID]
60
+ FROM [Orders] WHERE ([CustomerID] = @CustomerID)">
61
+ <SelectParameters>
62
+ <asp:ControlParameter ControlID="DropDownList1" Name="CustomerID"
63
+ PropertyName="SelectedValue" Type="String" />
64
+ </SelectParameters>
65
+ </asp:SqlDataSource>
66
+ <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
67
+ DataKeyNames="OrderID" DataSourceID="SqlDataSource2">
68
+ <Columns>
69
+ <asp:BoundField DataField="OrderID" HeaderText="OrderID"
70
+ InsertVisible="False"
71
+ ReadOnly="True" SortExpression="OrderID" />
72
+ <asp:BoundField DataField="CustomerID" HeaderText="CustomerID"
73
+ SortExpression="CustomerID" />
74
+ <asp:BoundField DataField="ShippedDate" HeaderText="ShippedDate"
75
+ SortExpression="ShippedDate" />
76
+ <asp:BoundField DataField="Freight" HeaderText="Freight"
77
+ SortExpression="Freight" />
78
+ <asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID"
79
+ SortExpression="EmployeeID" />
80
+ </Columns>
81
+ </asp:GridView>
82
+
83
+ </form>
84
+ </body>
85
+ </html>
86
+ ```