Search code examples
c#asp.netdrop-down-menudatatextfield

asp.net dropdownlist not showing DataTextField if there is a DataTextValueField too


I have a DataValueField and a DataTextField in my DropDownList. The data is from a DataSet and I want the dropdownlist to show the text field of my Dataset as preselected text. The Dataset is filled with data from a mysql table, containing "id" and "text". The DropDownList code is:

<asp:DropDownList runat="server" DataValueField="id" 
DataTextField="text" ID="statusList" CssClass="viewItemRight" 
AutoPostBack="true"></asp:DropDownList>

If there is no DataValueField-Tag the DropDownList shows correctly the text-value from my DataSet as preselected text in my DropDownList. But if I add the DataValueField the DataTextField doesnt showing any preselected Text in the DropDownList.

The code for the data is:

//load statusList
            cmd = new MySqlCommand();
            cmd.CommandText = "SELECT * FROM statuslist WHERE active = '1' ORDER BY sorting ASC";
            cmd.Connection = con;
            sda = new MySqlDataAdapter(cmd);
            ds = new DataSet();
            sda.Fill(ds);
            statusList.DataSource = ds;
            statusList.DataBind();
            statusList.Items.Insert(0, " ");

How can I use both, the DataValueField and the DataTextField?


Solution

  • Try something like this

    Code:

    DataTable dt = populatedd();
       statusList.DataSource = dt;
       statusList.DataTextField = "name";
       statusList.DataValueField = "id";
       statusList.DataBind();
    
        public DataTable populatedd()
        {
            string myQuery = "select id,name from yourtable order by name";
            SqlDataAdapter dap = new SqlDataAdapter(myQuery, con);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            return ds.Tables[0];
        }
    

    Markup

    <asp:DropDownList runat="server" ID="statusList" CssClass="viewItemRight" 
    AutoPostBack="true"></asp:DropDownList>