【问题标题】:Issue with Delete button in GridView in Visual StudioVisual Studio 中 GridView 中删除按钮的问题
【发布时间】:2014-01-21 16:44:03
【问题描述】:

这是我的代码:

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();
}

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

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

【问题讨论】:

    标签: c# winforms visual-studio gridview


    【解决方案1】:

    问题是您不知道如何选择行以及DataGridView 如何理解何时调用行选择。要选择一行,您必须单击行标题,或者如果您只想通过单击行上的任何单元格来选择行,只需将属性SelectionMode 设置为DataGridViewSelectionMode.FullRowSelect。那么SelectedRows应该至少有1个item,不再抛出index out of range异常。

    如果您打算允许用户一次删除 1 行,我认为您可以使用属性 CurrentRow 来获取当前选定的行,您也可以使用 CurrentCellCurrentCellAddress 并导出选定的行从他们那里排。

    【讨论】:

    • 这解决了异常的问题,但它仍然没有从数据库中删除条目...
    • 感谢您的帮助!
    【解决方案2】:

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

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

    【讨论】:

    • 我把它贴在上面了。请看一下。
    • 是的,我认为当您单击删除时,未选择 GridView 行时可能会出现错误。
    • 感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 2017-10-13
    相关资源
    最近更新 更多