如何在不是ListControl的元素上使用DataTextField?

时间:2013-01-25 02:14:51

标签: asp.net sql drop-down-menu datasource

所以这是我的情况:我有一个DropDownList,我在触发某个事件时填充。为了填充它,我执行一个返回两列的SQL查询:ID和Name。我使用DataSource / DataTextField / DataValueField将Name绑定到DropDownList,但我也想保存ID(在第二个查询中使用)。我怎么能这样做?

我尝试将ID保存到隐藏的输入字段,因为我想使用它但不将其显示给用户。但是输入不是ListControl,所以它不起作用。如何获取DropDownList中所选名称的匹配ID?

    string strConn = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
    SqlConnection con = new SqlConnection(strConn);
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "SELECT Id, Name FROM Users WHERE Age > 10";

    DataSet objDs = new DataSet();
    SqlDataAdapter dAdapter = new SqlDataAdapter();
    dAdapter.SelectCommand = cmd;
    con.Open();
    dAdapter.Fill(objDs);
    con.Close();
    if (objDs.Tables[0].Rows.Count > 0)
    {
        NameDropDown.DataSource = objDs.Tables[0];
        NameDropDown.DataTextField = "Name";
        NameDropDown.DataValueField = "Name";
        NameDropDown.DataBind();
        NameDropDown.Items.Insert(0, "--Select--");
    }
    else
    {
        NameDropDown.Items.Clear();
        NameDropDown.Items.Insert(0, "No names found");
    }

1 个答案:

答案 0 :(得分:1)

考虑:

if (objDs.Tables[0].Rows.Count > 0)
{
    NameDropDown.DataSource = objDs.Tables[0];
    NameDropDown.DataTextField = "Name";
    NameDropDown.DataValueField = "ID"; /*why wouldn't this be ID*/
    NameDropDown.DataBind();
    NameDropDown.Items.Insert(0, "--Select--");