开发者

binding data in list box control and retrieving the seleced value id

I have list box control where I am binding the values to the listbox

DataSet ds = new DataSet();
da.Fill(ds, "Employees");
ListBox1.DataSource = ds.Tables["Employees"].DefaultView; 
ListBox1.SelectedIndex = 0;
ListBox1.DataTextField = "FirstName";
ListBox1.DataValueField = "StaffID";
ListBox1.Databind();

after select ing the value . I have button once the user clicks this

protected void BtnClick(object sender, EventArgs e)  
  {       
 var selectedItems = (from item in listBox.Items.Cast<ListItem>()     where item.Selected        select item.Text).ToArray();   
     result.Text = "You selected: ";    
   result.Text += string.Join(",", selectedItems); 
   }

Right now I code inside the event gives me the selecte开发者_如何学运维d vlaues name. but I want to get the selected values index ex

ID  NAME
23  ram
34 tom
67 john

so if I select ram and john in code behind I need to get these vales ID that is 23, 67

Hope my question is clear

Thank you


you need to iterate your listbox items like..

 foreach (ListItem lstItem in lstProduct.Items)
    {
        if (lstItem.Selected)
        {
        }
    }


there was a small change to be made to make this work

protected void BtnClick(object sender, EventArgs e)
{
var selectedItems = (from item in listBox.Items.Cast() where item.Selected select **item.Value**).ToArray();
result.Text = "You selected: ";
result.Text += string.Join(",", selectedItems);
 }

this line

var selectedItems = (from item in listBox.Items.Cast() where item.Selected select item.Value).ToArray();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜