我将数据绑定到下拉列表,我想捕获第一个元素和第二个元素。但是,我试过的两种方法只捕获第一个元素?有人能告诉我如何补救吗?
这就是我如何绑定我的Drop Down
protected void BindDropDown()
{
var itemandprice = new List<ListItem>
{
new ListItem("Flannel Pajamas", "9"),
new ListItem("Fleece Jacket", "30"),
new ListItem("Flannel Shirt", "40")
}
this.dropdownlist123.DataSource = itemandprice;
this.dropdownlist123.DataBind();
}
选定的索引更改事件
protected void dropdownlist123_SelectedIndexChanged(object sender, EventArgs e)
{
this.txtOne.Text = dropdownlist123.SelectedValue;
this.txtTwo.Text = dropdownlist123.SelectedItem.Text;
}
两个文本框中都有“Flannel睡衣”的价值,而不是我之后的法兰绒睡衣和9
为了捕获这两个元素,我需要做什么?
编辑1
根据@Alex Krups的建议我尝试了这种语法,但这给了我与上面语法相同的输出
this.txtOne.Text = dropdownlist123.SelectedItem.Value;
this.txtTwo.Text = dropdownlist123.SelectedItem.Text;
答案 0 :(得分:1)
您需要为DropDownList设置DataTextField和DataValueField。
请试试这个:
this.DropDownList1.DataTextField = "Text";
this.DropDownList1.DataValueField = "Value";
this.DropDownList1.DataSource = itemandprice;
this.DropDownList1.DataBind();
希望这有帮助〜
答案 1 :(得分:0)
尝试
this.txtOne.Text = dropdownlist123.SelectedItem.Value;
this.txtTwo.Text = dropdownlist123.SelectedItem.Text;