Use this
YourComboBox.DataSource = YourList<Category>;
YourComboBox.DisplayMember = StringNameOfProperty;
to fill your Combobox. To get the item behind the Propery-Value use:
var item = (Category) YourComboBox.SelectedItem;
Domanda
I am developing simple prof of concept using C# winform , and Nhibernate as ORM,
its very simple just adding an item. and each item have a Foreign Key to Category table.
Sorry i couldnt upload image for the class diagram, i am not allowed yet to upload images. so the classes are
public class Category
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual string NameArabic { get; set; }
public static bool AddCategory(Category category)
{
using (var session=NhibernateHelper.OpenSession())
{
using (var transaction=session.BeginTransaction())
{
session.SaveOrUpdate(category);
transaction.Commit();
}
return true;
}
}
public static IList<Category> GetAll()
{
using (var session=NhibernateHelper.OpenSession())
{
return session.QueryOver<Category>().List<Category>();
}
}
}
public class Item
{
public virtual Guid Id { get; set; }
public virtual string Description { get; set; }
public virtual Category Category { get; set; }
public static bool AddItem(Item item)
{
using (var session = NhibernateHelper.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
session.SaveOrUpdate(item);
transaction.Commit();
}
return true;
}
}
}
When the users click insert item button it should execute the following code
private void insertItem_Click(object sender, EventArgs e)
{
Model.Item item = new Item
{
// allCategories is IList<Category> contain all categories retrieved from Database
Category = (from category in allCategories
where category.Id == Guid.Parse(comboBox1.SelectedValue.ToString())
select category).FirstOrDefault(),
Description = textBox1.Text // the name text box
};
if (Model.Item.AddItem(item))
MessageBox.Show("Transaction Completed");
}
My problem is, since i am using Nhibernate and to avoid inserting new category in the database each time i add item , i should pass a category object with Guid as the same as the saved one in the database, so i used the linq query as shown above that queries on all categories list retrieved from the database which i think is bad approach.
is there suggestion to bind the allCategories List directly to the comboBox, in which i can use a specific property to point at the derived object Guid that currently listed in the comboBox.
Class Mapping
public CategoryMap()
{
Id(x => x.Id);
Map(x => x.Name);
Map(x => x.NameArabic);
}
public ItemMap()
{
Id(x => x.Id);
Map(x => x.Description);
References(x => x.Category);
}
Thanks,
Soluzione
Use this
YourComboBox.DataSource = YourList<Category>;
YourComboBox.DisplayMember = StringNameOfProperty;
to fill your Combobox. To get the item behind the Propery-Value use:
var item = (Category) YourComboBox.SelectedItem;