Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does binding a DropDownList function differently than manually adding ListItems?

Snippet One

I add list items to my drop down one at a time.

var ddlHour = new DropDownList {ID = "ddlHour" + i};
ddlHour.Items.Add(new ListItem("12 AM", "0:00"));
ddlHour.Items.Add(new ListItem("1 AM", "1:00"));
ddlHour.Items.Add(new ListItem("2 AM", "2:00"));
Console.WriteLine(ddlHour.Items[0].Value); 
// Prints 0:00

Snippet Two

I bind my drop down to an array of list items.

var hourItems = new[]
{
    new ListItem("12 AM", "0:00"), // "Text", "Value"
    new ListItem("1 AM", "1:00"),
    new ListItem("2 AM", "2:00")
};
var ddlHour = new DropDownList {ID = "ddlHour" + i, DataSource = hourItems};
ddlHour.DataBind();
Console.WriteLine(ddlHour.Items[0].Value); 
// Prints 12 AM

After the first snippet executes, I inspect the values of each item and find "0:00", "1:00", and "2:00". Exactly what I expect.

After the second snippet executes, I inspect the values of each item and find "12 AM", "1 AM", and "2 AM". Not what I expect. What happened to my values?

like image 923
Rainbolt Avatar asked Jun 10 '26 19:06

Rainbolt


1 Answers

They are same. Only different is that if you use DataSource, you need to specify DataTextField and DataValueField.

...
ddlHour.DataBind();
ddlHour.DataTextField = "Text";
ddlHour.DataValueField = "Value";
Console.WriteLine(ddlHour.Items[0].Value); 
like image 158
Win Avatar answered Jun 13 '26 12:06

Win



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!