我的系统中有一个组合框,其dropdownstyle设置简单,也可以自动完成。在键入记录的前几个字母后选择值时,系统将引发NullReferenceException。
我已将组合框与数据库绑定,并分别将DisplayMember设置为Name,将Value Member设置为ID。当我在组合框按下事件中按Enter键时,我想选择产品并在消息中显示其ID,但它不起作用
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事件
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
{
MessageBox.Show(combo_searchName.SelectedValue.ToString());
}
答案 0 :(得分:0)
首先检查数据表的数据。如果数据表中没有可用数据。然后它将引发异常。