为什么绑定DropDownList函数与手动添加listitem不同?

时间:2022-10-21 06:36:27

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.

在执行第一个代码片段之后,我检查每个项目的值并找到“0:00”、“1:00”和“2:00”。正是我希望的。

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?

在执行第二个代码片段之后,我检查每个项目的值并找到“12 AM”、“1 AM”和“2 AM”。不是我所期望的。我的价值观怎么了?

1 个解决方案

#1


3  

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

他们是相同的。唯一不同的是,如果您使用数据源,您需要指定DataTextField和DataValueField。

...
ddlHour.DataBind();
ddlHour.DataTextField = "Text";
ddlHour.DataValueField = "Value";
Console.WriteLine(ddlHour.Items[0].Value); 

#1


3  

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

他们是相同的。唯一不同的是,如果您使用数据源,您需要指定DataTextField和DataValueField。

...
ddlHour.DataBind();
ddlHour.DataTextField = "Text";
ddlHour.DataValueField = "Value";
Console.WriteLine(ddlHour.Items[0].Value);