我有一个绑定(bind)到 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>
我想将第三个数据库列绑定(bind)到另一个属性(不是值),例如将数据库表列 DefaultBit
绑定(bind)到 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 绑定(bind)到 DropDownList,或者是否应该打开连接并使用 SqlReader 迭代结果并更新DropDownList“手动”或其他一些更优雅的解决方案。
最佳答案
请尝试以下解决方案:
添加
DropDownList
和SqlDataSource
标记为(请注意,我已添加OnDataBound="ddlist_DataBound"
和 select 中的第三列声明)<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()); } }
我已经在应用程序中对其进行了测试,并且运行良好。
关于c# - 使用 SqlDataSource 时向 DropDownList 项目添加除值之外的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30788082/