【问题标题】:Assign Different Value and Text to Dropdown List Items为下拉列表项分配不同的值和文本
【发布时间】:2014-12-10 16:36:12
【问题描述】:

我正在尝试使用来自 batabase 的数据填充页面加载的下拉列表。

在填充时,我希望下拉项 (<option>) 的显示文本不同于 <option> 的“value

例如:下拉列表将在 UI 上将“Title”(来自 db 的列)显示为文本,但 <option> 的“value”应该是“ID”(来自 db 的列)

我如何做到这一点?

目前我的代码是这样的:(drpReleaseTitle是下拉列表的ID)

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
        con1.Open();

        SqlCommand releaseTitlecmd = new SqlCommand("select Title from LWMDemo_ReleaseInfo order by ReleaseID", con1);
        SqlDataReader releaseTitledr = releaseTitlecmd.ExecuteReader();
        while (releaseTitledr.Read())
        {
            drpReleaseTitle.Items.Add(releaseTitledr.GetValue(0).ToString());
        }
        con1.Close();
    }
}

【问题讨论】:

    标签: c# asp.net database drop-down-menu code-behind


    【解决方案1】:

    试试这个

    drpReleaseTitle.Items.Add(new ListItem("yourtext", "yourvalue"));
    

    【讨论】:

      【解决方案2】:

      最好使用数据集而不是数据读取器,因为它使用断开连接的架构,因此您可以在关闭连接后使用

       protected void Page_Load(object sender, EventArgs e)
      {
          if (!IsPostBack)
          {
              SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
              con1.Open();
      
              SqlCommand releaseTitlecmd = new SqlCommand("select Title from LWMDemo_ReleaseInfo order by ReleaseID", con1);
             SqlDataAdapter sda = new SqlDataAdapter();
              sda.SelectCommand = Cmd;
              sda.Fill(ds);
              if(ds!=null && ds.table.count>0){
              if(ds.table[0]!=null && ds.table[0].rows.count>0){
                  drpReleaseTitle.DataSource=ds.table[0].Title;  //Title Column
                   drpReleaseTitle.DataSourceID=ds.table[0].ID;  //ID Column
              }
          }
              con1.Close();
          }
      }
      

      【讨论】:

        【解决方案3】:

        如果您尝试将字符串添加到下拉列表中的项目,它将创建一个项目,该项目将包含文本和值作为您的字符串。您需要添加新的 ListItem。 ListItem 包含以文本和值作为参数的构造函数。有关此课程的更多信息,您可以阅读here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-22
          • 2010-11-04
          相关资源
          最近更新 更多