Visual Studio中的GridView中的“删除”按钮问题

时间:2014-01-21 16:44:03

标签: c# winforms visual-studio gridview

这是我的代码:

private void Bind()
        {
            SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dido\documents\visual studio 2012\Projects\CourseProjectCars\CourseProjectCars\DataCars.mdf;Integrated Security=True;Connect Timeout=30");
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("select * from SuperCars", con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
        }





private void button4_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dido\documents\visual studio 2012\Projects\CourseProjectCars\CourseProjectCars\DataCars.mdf;Integrated Security=True;Connect Timeout=30");
    SqlCommand delcmd = new SqlCommand();
    if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
    {
        delcmd.CommandText = "DELETE FROM SuperCars WHERE Car='%" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "%'";
        con.Open();
        delcmd.Connection = con;
        delcmd.ExecuteNonQuery();
        con.Close();
        dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
        MessageBox.Show("Row Deleted");
    }
    Bind();
}

我想在我的应用程序中添加一个删除按钮。当我选择一行并单击删除按钮时,它会抛出以下异常:

  

指数超出范围。必须是非负数且小于集合的大小。

2 个答案:

答案 0 :(得分:1)

问题是您不知道如何选择行以及DataGridView在调用 选择 行时的理解方式。要选择行,您必须单击行标题,或者如果只想通过单击行上的任何单元格来选择行,只需将属性SelectionMode设置为DataGridViewSelectionMode.FullRowSelect即可。那么SelectedRows应该至少有一个项目,不应再抛出索引超出范围的异常。

如果您打算允许用户一次删除1行,我认为您可以使用属性CurrentRow来获取当前选定的行,您也可以使用CurrentCell或{{1并从中导出所选行。

答案 1 :(得分:0)

请在Bind()函数中显示代码。我认为记录没有在数据库中删除,当你在那时调用Bind()函数时,记录再次在gridview中绑定。 我认为你的删除查询是错误的,如果你想删除有汽车作为单元格[0]值的记录,那么查询将如下:

delcmd.CommandText = "DELETE FROM SuperCars WHERE Car Like '%" +dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "%'";