在数据网格视图中,删除不能在选定的数据中工作
本文关键字:数据 工作 不能 数据网 网格 视图 删除 | 更新日期: 2023-09-27 18:02:06
当用户点击"删除"时,我试图同时从数据网格和数据库中删除选定的数据。它不工作,错误消息显示"索引超出范围"。必须非负且小于集合的大小。参数名称:index"有人能帮我解决这个编码吗?
private void btnDeleteCustomer_Click(object sender, EventArgs e)
{
string strSqlConnection = @"Data Source = KK'SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = JeanDB";
if ((dgvCustomerView.Rows.Count>0) && (dgvCustomerView.SelectedRows[1].Index != dgvCustomerView.Rows.Count))
{
SqlConnection sqlconn = new SqlConnection(strSqlConnection);
DataSet dsCustomers = new DataSet();
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = @"Delete from dbo.Customers WHERE CustomerID = @iCustomerID";
SqlDataAdapter sdaCustomer = new SqlDataAdapter(QueryDelCus, sqlconn);
sqlconn.Open();
DataTable dtEmployee = new DataTable("Customers");
sdaCustomer.Fill(dsCustomers, "Customers");
sqlconn.Close();
dgvEmpView.Rows.RemoveAt(dgvEmpView.SelectedRows[0].Index);
MessageBox.Show("Deleted Successfully");
}
}
除了删除你可以重新绑定grid:
dgvEmpView.DataSource = dsCustomers;
dgvEmpView.DataBind();
MessageBox.Show("Deleted Successfully");
,删除时使用ExecuteNonQuery
:
SqlCommand cmd = new SqlCommand(QueryDelCus, sqlconn);
sqlconn.Open();
cmd.ExecuteNonQuery();
除非你有两行选择引用SelectedRows[1]是错误的。数组索引总是从0开始。(可能它只是一个类型,因为其他行正确地引用了要删除的行)
if ((dgvCustomerView.Rows.Count>0) &&
(dgvCustomerView.SelectedRows[0].Index != dgvCustomerView.Rows.Count))
{
....
,但是,要删除数据库中的行,您不需要使用SqlDataAdapter。您可以直接使用SqlCommand
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = @"Delete from dbo.Customers WHERE CustomerID = @iCustomerID";
SqlCommand cmd = new SqlCommand(QueryDelCus, sqlconn);
cmd.Parameters.AddWithValue("@iCustomerID", iCustomerID);
sqlconn.Open();
cmd.ExecuteNonQuery();
最后,您可以简单地从网格中删除选中的行,而无需进一步查询
dgvEmpView.Rows.RemoveAt(dgvEmpView.SelectedRows[0].Index);
如果不使用sql参数,则使用普通sql查询。
DataSet dsCustomers = new DataSet();
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = @"Delete from dbo.Customers WHERE CustomerID = "+ iCustomerID.ToString();
SqlDataAdapter sdaCustomer = new SqlDataAdapter(QueryDelCus, sqlconn);