我有一个sqlconnection模板,在没有问题之前我已经使用了此代码。直到我想在datagridview中使用它。
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentRow != null)
{
try
{
SQLConn.sqL = "SELECT ProductID,PCode,PName FROM Products WHERE PCode='" + txtBarcode.DataGridView.CurrentCell.Value.ToString() + "'";
SQLConn.ConnDB();
SQLConn.cmd = new SqlCommand(SQLConn.sqL, SQLConn.conn);
SQLConn.dr = SQLConn.cmd.ExecuteReader();
while (SQLConn.dr.Read())
{
dataGridView1.Rows[e.RowIndex].Cells[1].Value = SQLConn.dr["ProductID"].ToString();
dataGridView1.Rows[e.RowIndex].Cells[2].Value = SQLConn.dr["PName"].ToString();
}
}
catch (Exception ex)
{
Interaction.MsgBox(ex.ToString());
}
finally
{
SQLConn.cmd.Dispose();
SQLConn.conn.Close();
}
}
}
我认为该事件的多个调用都进入了该函数,从而导致了问题。请添加SQLConn.dr.Close()以在finally子句中关闭打开的阅读器。
尝试一下
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentRow != null)
{
try
{
SQLConn.sqL = "SELECT ProductID,PCode,PName FROM Products WHERE PCode='" + txtBarcode.DataGridView.CurrentCell.Value.ToString() + "'";
SQLConn.ConnDB();
SQLConn.cmd = new SqlCommand(SQLConn.sqL, SQLConn.conn);
SQLConn.dr.Close()
SQLConn.dr = SQLConn.cmd.ExecuteReader();
while (SQLConn.dr.Read())
{
dataGridView1.Rows[e.RowIndex].Cells[1].Value = SQLConn.dr["ProductID"].ToString();
dataGridView1.Rows[e.RowIndex].Cells[2].Value = SQLConn.dr["PName"].ToString();
}
}
catch (Exception ex)
{
Interaction.MsgBox(ex.ToString());
}
finally
{
SQLConn.cmd.Dispose();
SQLConn.conn.Close();
}
}
}