-1

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());
}
  • @AhmedAbdelhameed I checked and it is not the case.... because when I select an item in the combobox without the use of autocompletemode it works. and when i change the combobox dropdownstyle to dropdownlist it works. – Mohammed Imadh Dec 31 '18 at 09:05

1 Answers1

0

First check data of data table. If no data available in data table. Then it will throw exception.

S.Maneesh
  • 60
  • 6