删除选定的行datagridview错误 [英] delete selected row datagridview error

查看:77
本文介绍了删除选定的行datagridview错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了以下代码:

i used this code:

SqlConnection Conn = new SqlConnection(@"server=.\Mssql2008;database=Basij;integrated security=true;");
           SqlCommand delcmd = new SqlCommand();
           if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
           {
               delcmd.CommandText = "DELETE FROM Tblregister WHERE Fldcode=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "";
               Conn.Open();
               delcmd.ExecuteNonQuery();
               Conn.Close();
               dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
           }



但是当我单击button1时,出现此错误:
ExecuteNonQuery:连接属性尚未初始化.



but when i click button1 this error apear:
ExecuteNonQuery: Connection property has not been initialized.

推荐答案

稍作修改即可.
您可以像这样编写代码:-
Little modify your code.
you write your code like:-
SqlConnection Conn = new SqlConnection(@"server=.\Mssql2008;database=Basij;integrated security=true;");
SqlCommand delcmd = new SqlCommand();
if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
{
delcmd.CommandText = "DELETE FROM Tblregister WHERE Fldcode=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "";
Conn.Open();
delcmd.Connection=Conn;//this point is missing in your code.
delcmd.ExecuteNonQuery();
Conn.Close();
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
}


正如Rakesh所指出的那样,您需要指定数据命令将使用哪个连接.您可能会找到 [
As Rakesh have pointed out, you need to specify which connection your data command will use. You might find this[^] useful.


Rakesh是对的,您也可以使用以下代码:

Hi Rakesh is Right and you can also use this code:

SqlConnection Conn = new SqlConnection(@"server=.\Mssql2008;database=Basij;integrated security=true;");
SqlCommand delcmd = new SqlCommand("DELETE FROM Tblregister WHERE Fldcode=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "",Conn);
if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
{
Conn.Open();
delcmd.ExecuteNonQuery();
Conn.Close();
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
}


这篇关于删除选定的行datagridview错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆