I have combobox in system with it's dropdownstyle set simple and also to autocomplete. When I select value after typing the first few letters of a record the system throws a NullReferenceException.
I have binded the combobox with database and have set the DisplayMember as Name and Value Member as ID respectively. When I hit the enter key on the combobox keydown event I want to select the product and show the id of it in a message but it isn't working
private void FillCombobox()
{
DataTable dt = new DataTable();
try
{
// Set the connection string in the Solutions Explorer/Properties/Settings object (double-click)
using (EmpireDbContext dbcontext = new EmpireDbContext())
{
var query = from c in dbcontext.Inventory
orderby c.ProductName
select new
{
c.ProductCode,
c.ProductName
};
if (query == null)
{
throw new ArgumentNullException();
}
dt.Columns.Add(
new DataColumn()
{
DataType = System.Type.GetType("System.String"),//or other type
ColumnName = "Name",
}
);
dt.Columns.Add(
new DataColumn()
{
DataType = System.Type.GetType("System.Int32"),
ColumnName = "ID",
}
);
foreach (var element in query)
{
var row = dt.NewRow();
row["Name"] = element.ProductName;
row["ID"] = element.ProductCode;
dt.Rows.Add(row);
}
}
}
catch (Exception ex)
{
throw ex;
}
combo_searchName.DataSource = dt;
combo_searchName.ValueMember = "ID";
combo_searchName.DisplayMember = "Name";
}
combobox Keydown event
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
{
MessageBox.Show(combo_searchName.SelectedValue.ToString());
}