[英]How to get Id from ComboBox in C# windows Form Application
我有一個這樣填充的ComboBox
:
List<Category> CategList = new Category().getAllCategory();
foreach (Category cat in CategList)
{
ComboForCategory.Items.Add(cat.CategoryName);
}
ComboBox
成功顯示所有CategoryName
詳細信息...現在我需要從選定的Name
獲取CategoryID
...
然后我曾經像這樣獲得CategoryID
:
Item ob = new Item();
ob.category.CategoryId = ComboForCategory.SelectedValue.ToString();
但它顯示錯誤。 為什么? 如何從選定的Name
獲取CategoryID
?
在后面的代碼中,您需要指定 ValueMember 屬性。 然后,您可以使用 DisplayMember 指定要顯示的對象的哪個屬性。
List<Category> CategList = new Category().getAllCategory();
ComboForCategory.DataSource = CategList;
ComboForCategory.DisplayMember = "CategoryName";
ComboForCategory.ValueMember = "CategoryId";
然后當你想獲取 SelectedValue 時,你可以這樣調用它:
ob.category.CategoryId = Convert.ToInt32(ComboForCategory.SelectedValue);
(不需要使用 ToString() )。
使用隱藏 ID 從數據庫設置組合comboBox
值
var collection = dbContext.Category;
comboBox1.DisplayMember = "Column-Name";
comboBox1.ValueMember = "ID";
comboBox1.DataSource = collection;
要在組合comboBox
設置帶有 id 的值,只需寫
comboBox.SelectedValue = "Id";
只需復制和粘貼
model.CategoryID = Guid.Parse(comboBox1.SelectedValue.ToString());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.