从列表框中获取选定的值 [英] get selected value from list box
本文介绍了从列表框中获取选定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码将项目绑定到列表框:
Hi,
I''m using the following code to bind the items to a List box:
listAll.DataSource = string.Empty;
listAll.DataTextField = string.Empty;
listAll.DataValueField = string.Empty;
SqlCommand cmd = new SqlCommand("select ID,Name from Machine_Area", con);
SqlDataReader dr = cmd.ExecuteReader();
//listAll.DataTextField=dr["Name"].ToString();
//listAll.DataValueField=dr["ID"].ToString();
while (dr.Read())
{
listAll.DataTextField = dr["Name"].ToString();
listAll.DataValueField = dr["ID"].ToString();
listAll.Items.Add(dr["Name"].ToString());
listAll.DataBind();
}
dr.Close();
我想获取所选项目的数据值.
我尝试使用
I want to get the datavalue of the selected item.
I tried with
listAll.SelectedValue & listAll.SelectedItem.Value
但是我在dr ["Name"]字段中获取数据,而不是在dr ["ID"]字段中获取数据.
如何获得列表框所选项目的dr ["ID"]值?
谢谢.
But I''m getting data in the dr["Name"] field, not dr["ID"] filed.
How can I get the dr["ID"] value for the list box selected item?
Thank You.
推荐答案
首先,您的数据绑定代码令人困惑.可能像下面的
l
First your databind code is confusing. It may be like below
l
SqlCommand cmd = new SqlCommand("select ID,Name from Machine_Area", con);
DataTable dt=new DataTable();
con.Open()
using(con)
{
dt.Load(cmd.ExecuteReader());
}
listAll.DataSource=dt;
listAll.DataTextField = dr["Name"].ToString();
listAll.DataValueField = dr["ID"].ToString();
那么您可以将listAll SelectedValue作为
then you can get the listAll SelectedValue as
DataRowView drv=(DataRowView)listAll.SelectedItem;
int selectedVal=Convert.ToInt32(drv["ID"]);
string selectedText=drv["Name"].ToString();
这篇关于从列表框中获取选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文