我有一个绑定到SqlDataSource的DropDownList,如下所示:
<asp:DropDownList ID="ddlist" AppendDataBoundItems="True" DataSourceID="SqlDataSource1" DataTextField="name" DataValueField="value" AutoPostBack="True" runat="server">
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" ConnectionString="<%$ ConnectionStrings:myConnectionString %>" SelectCommand="SELECT [name], [value] FROM [myTable]" runat="server"></asp:SqlDataSource>
我想将第三个数据库列绑定到另一个属性(不是值),比如数据库表列DefaultBit
绑定到ListItem属性data-default
,以便DropDownList呈现为
<select>
<option></option>
<option value="1" data-default="1">Line 1</option>
<option value="2" data-default="0">Line 2</option>
</select>
我假设我需要在代码隐藏文件中以编程方式执行此操作,但我不清楚是否仍然将SqlDataSource绑定到DropDownList,或者我是否应该打开连接并使用SqlReader迭代结果并更新DropDownList“手动”或其他一些更优雅的解决方案。
答案 0 :(得分:1)
请尝试以下解决方案:
添加DropDownList
和SqlDataSource
标记为(请注意我在select语句中添加了OnDataBound="ddlist_DataBound"
和第三列)
<asp:DropDownList ID="ddlist" AppendDataBoundItems="True" OnDataBound="ddlist_DataBound"
DataSourceID="SqlDataSource1" DataTextField="name" DataValueField="value"
AutoPostBack="True" runat="server">
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" ConnectionString=
"<%$ ConnectionStrings:myConnectionString %>" SelectCommand="SELECT [name], [value],
[DefaultBit] FROM [myTable]" runat="server">
</asp:SqlDataSource>
将方法"ddlist_DataBound"
后面的代码添加为:(请注意row[0]
是名称,row[1]
是值,row[2]
是DefaultBit)
protected void ddlist_DataBound(object sender, EventArgs e) {
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.DataView dv = (System.Data.DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
dt = dv.ToTable();
foreach (System.Data.DataRow row in dt.Rows) {
ddlist.Items.FindByValue(row[1].ToString()).Attributes.Add("data-default", row[2].ToString());
}
}
我在一个应用程序中对它进行了测试并且工作得非常好。