如何使用C#的WinForms获得所选择的项目ID列表框中

问题描述:

我有列表框(lstcategories)..填充通过使用下面的代码从数据库来的项目...如何使用C#的WinForms获得所选择的项目ID列表框中

 private void getcategorynames() 
    { 
     var categorytypes = (from categories in age.categories 
         select categories.category_Name).ToList(); 


     foreach (string item in categorytypes) 
     { 

      listcategories.Items.Add(item); 


     } 

我的问题是,如果我点击列表框,我需要做些什么项目..这样

,如果我的类别名称(列表框项目)点击我需要在选择的类别名称传递到数据库

可以在任何一个请帮助...

+0

你需要了解如何为列表框绑定一个事件。 –

ListBox.Items是对象的集合,这样你就可以存储类对象本身,而不是它的字符串表示。

age.Categories.ToList().ForEach((c) => listcategories.Items.Add(c)); 

然后在ListBox.SelectedIndexChanged

Category category = (Category)listcategories.SelectedItem; 
// Do something with category.Id 

如果你想这样做,所有内嵌

private void getcategorynames() { 
    age.Categories.ToList().ForEach((c) => listcategories.Items.Add(c)); 
    listcategories.SelectedIndexChanged += (sender, e) => { 
     Category category = (Category)listcategories.SelectedItem; 
     // Do something with category.Id 
    }; 
} 
+0

很多谢谢..安德森..... –

做这样的事情。当你得到选定的listitem时,它将是类型Cat,其中包含类别的id和名称。

public class Cat 
    { 
      public int Id { get;set;} 
      public string Name { get;set;} 

     public override string ToString() 
     { 
      return this.Name; 
      } 

    } 

    private void getcategorynames() 
     { 
      var categorytypes = (from categories in age.categories 
          select categories.category_Name).ToList(); 

listcategories.SelectedIndexChanged += new EventHandler(listcategories_SelectedIndexChanged); 

      foreach (var c in categorytypes.select(p=> new Cat { Id = p.category_Id, Name = p.category_Name})) 
      { 

       listcategories.Items.Add(c); 


      } 

void listcategories_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      Cat selected = (Cat)(sender as ListBox).SelectedItem; 
     } 
+0

嗨..我需要在列表框中添加文本像这样的“类别”列表框中显示此列表之前如何做到这一点..... –

也许这将帮助:

DataTable table = new DataTable(); 
    public Form1() 
    { 
     InitializeComponent(); 

     //you fill the table from database, I will show you my example (becuase I dont have dataBase)! 
     table.Columns.Add("CategoryID", typeof(int)); 
     table.Columns.Add("CategoryName", typeof(string)); 
     table.Rows.Add(1, "name 1"); 
     table.Rows.Add(2, "name 2"); 
     table.Rows.Add(3, "name 3"); 

     listBox1.DataSource = new BindingSource(table, null); 
     listBox1.DisplayMember = "CategoryName"; 
     listBox1.ValueMember = "CategoryID"; 
    } 

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     if (listBox1.SelectedIndex > -1) 
     { 
      DataRowView data = listBox1.SelectedItem as DataRowView; 
      int id = int.Parse(data["CategoryID"].ToString()); 
      string name = data["CategoryName"].ToString(); 
     } 
    }