Question

I am filling my DropDownList with the following code;

 while (myDataReader.Read())
                {

                    DropDownList1.Items.Add(myDataReader[0].ToString());
                    DropDownList1.DataValueField = myDataReader[1].ToString();
                    DropDownList1.DataTextField = myDataReader[0].ToString();

                }

But regardless of what is selected in the DropDownList1, the DataValue is always the last DataValue to be read from the while loop.

What am I doing wrong?

Was it helpful?

Solution

Instead of using myDataReader, I bound the dropdownList to a data source

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);

SqlCommand cmd = new SqlCommand("Select * from students", con);

SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();
da.Fill(ds);

DropDownList1.DataTextField = ds.Tables[0].Columns["FullName"].ToString();
DropDownList1.DataValueField = ds.Tables[0].Columns["id"].ToString();

DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataBind();

OTHER TIPS

So it looks like you want to use Database Column Names as the Data Value fields. But you're actually providing the Column Values, not the Column Names, as the Data Value Fields. Your code should look like this:

DropDownList1.DataValueField = "ValueColumn"; //name of the value column, such as 'id' from the database
DropDownList1.DataTextField = "NameColumn"; //name of the descriptive column, such as 'name'
while (myDataReader.Read())
{
     //also, we removed the 'ToString' because we want to provide the datarow object, not the converted string value
     DropDownList1.Items.Add(myDataReader[0]);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top