Click here to Skip to main content
15,911,030 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I'm using the following code to bind the items to a List box:

C#
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
SQL
listAll.SelectedValue & listAll.SelectedItem.Value

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.
Posted
Updated 1-Nov-12 22:59pm
v2

1 solution

First your databind code is confusing. It may be like below
l
C#
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();


then you can get the listAll SelectedValue as

C#
DataRowView drv=(DataRowView)listAll.SelectedItem;
int selectedVal=Convert.ToInt32(drv["ID"]);
string selectedText=drv["Name"].ToString();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900