Chris Purves
Chris Purves

Reputation: 399

add attribute other than value to DropDownList items when using SqlDataSource

I have a DropDownList bound to a SqlDataSource as follows:

<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>

I would like to bind a third database column to another attribute (not value), say database table column DefaultBit to ListItem attribute data-default so that the DropDownList renders as

<select>
    <option></option>
    <option value="1" data-default="1">Line 1</option>
    <option value="2" data-default="0">Line 2</option>
</select>

I assume I need to do this programmatically in the code-behind file, but it's not clear to me if I would still bind a SqlDataSource to the DropDownList or if I should open a connection and iterate through the results using SqlReader and update the DropDownList "manually" or some other more elegant solution.

Upvotes: 2

Views: 3413

Answers (1)

ManP
ManP

Reputation: 231

Please try following solution:

  1. Add DropDownList and SqlDataSource mark up as (please note I have added OnDataBound="ddlist_DataBound" and third column in select statement)

    <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>
    
  2. Add code behind method "ddlist_DataBound" as:(please note row[0] is name, row[1] is value and row[2] is 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());
        }
    }
    

I have tested it in an application and works beautifully.

Upvotes: 2

Related Questions