从下拉列表中访问信息

本文关键字:信息 访问 下拉列表 | 更新日期: 2023-09-27 18:17:59

我正在将数据绑定到一个下拉列表,并且我想捕获第一个元素和第二个元素。但是,我尝试的两种方法都只捕获第一个元素吗?有人能告诉我怎么补救吗?
这是我如何绑定下拉菜单

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;
}


两个文本框都有值"法兰绒睡衣"在它而不是我之后,这将是法兰绒睡衣和9

为了捕获这两个元素,我需要做些什么?

编辑1
根据@Alex Krups的建议,我尝试了这种语法,但这给了我与上面的语法相同的输出

this.txtOne.Text = dropdownlist123.SelectedItem.Value;
this.txtTwo.Text = dropdownlist123.SelectedItem.Text;

从下拉列表中访问信息

您需要为下拉列表设置DataTextField和DataValueField。

Please try this:

this.DropDownList1.DataTextField = "Text";
this.DropDownList1.DataValueField = "Value"; 
this.DropDownList1.DataSource = itemandprice;
this.DropDownList1.DataBind();

希望有帮助~

Try

this.txtOne.Text = dropdownlist123.SelectedItem.Value;
this.txtTwo.Text = dropdownlist123.SelectedItem.Text;