关闭阅读器版本2时无效尝试调用MetaData

问题描述 投票:0回答:2

我有一个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();
            }
        }
    }
c# sql-server datagridview metadata
2个回答
0
投票

我认为该事件的多个调用都进入了该函数,从而导致了问题。请添加SQLConn.dr.Close()以在finally子句中关闭打开的阅读器。


0
投票

尝试一下

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();
            }
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.