我正在尝试根据组合框中选择的项目填充文本框。问题是它在加载时抛出以下错误,我在visual studio中按next .. next。它做了我真正想做的事情。
如何解决负载问题。
表格加载的代码是
private void UpdateProduct_Load(object sender, EventArgs e)
{
DataSet ds = GetAllItems();
comboBox2.DataSource = ds.Tables[0];
comboBox2.DisplayMember = "Product Name";
comboBox2.SelectedIndex = 0;
}
组合框的选定索引的代码是
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
// string selectedText = this.comboBox2.GetItemText(this.comboBox2.SelectedItem);
DataSet d = GetProductInfo(comboBox2.Text);
if (d.Tables.Count > 0)
{
textBox2.Text = d.Tables[0].Rows[0]["Quantity"].ToString();
textBox3.Text = d.Tables[0].Rows[0]["Color"].ToString();
textBox4.Text = d.Tables[0].Rows[0]["Size"].ToString();
textBox5.Text = d.Tables[0].Rows[0]["Price"].ToString();
}
}
第一次加载表单时我只有问题。
GetProductInfo代码
public DataSet GetProductInfo(string product)
{
DataSet dataSet = new DataSet();
OleDbConnection oleConn = new OleDbConnection(connString);
try
{
oleConn.Open();
string sql = "SELECT [Quantity], [Color], [Size], [Price] FROM [Product] WHERE [Product Name]= '" + product + "'";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, oleConn);
dataAdapter.Fill(dataSet, "Product");
}
catch (Exception ex)
{
MessageBox.Show("An exception has been occured\n" + ex.ToString());
Console.WriteLine(ex.ToString());
}
finally
{
oleConn.Close();
}
if (dataSet.Tables["Product"].Rows.Count <= 0)
return null;
return dataSet;
}
堆栈跟踪
System.NullReferenceException occurred
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=Purchase Management
StackTrace:
at Purchase_Management.UpdateProduct.comboBox2_SelectedIndexChanged(Object sender, EventArgs e) in c:\Users\Amrit\Desktop\Purchase Management\Purchase Management\UpdateProduct.cs:line 99
InnerException:
答案 0 :(得分:1)
使用 SelectionChangeCommitted 事件,而不是使用SelectedIndexChanged。这样可以避免所有这些问题,因为它只会在用户更改所选项目时触发,而不是在初始化组合框时触发。
答案 1 :(得分:0)
您的方法返回null。这就是抛出错误的原因
DataSet dstProduct = new DataSet();
dstProduct = GetProductInfo(comboBox2.Text);
然后尝试
if(dstProduct.Tables.Count>0 && dstProduct.Tables[0].Rows.Count >0)
{
// then do stuff.
}
答案 2 :(得分:0)
因为.Count
在d = null
的情况下触发了异常。
声明DataSet d = new DataSet();
答案 3 :(得分:0)
只需添加if (!string.IsNullOrEmpty(productName))
语句,您就可以了:
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
var productName = comboBox2.Text;
if (!string.IsNullOrEmpty(productName)) {
DataSet d = GetProductInfo(productName);
if (d.Tables.Count > 0)
{
textBox2.Text = d.Tables[0].Rows[0]["Quantity"].ToString();
textBox3.Text = d.Tables[0].Rows[0]["Color"].ToString();
textBox4.Text = d.Tables[0].Rows[0]["Size"].ToString();
textBox5.Text = d.Tables[0].Rows[0]["Price"].ToString();
}
}
}