如何从datagridview c#中删除数据?

时间:2018-04-28 13:22:10

标签: c# winforms datagridview local-database

当我使用下面的代码时,它会从datagridview中删除一行,但是当我刷新页面时它不会...

    private void DeleteData_Click(object sender, EventArgs e)
    {

        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Selected)
            {
                dataGridView1.Rows.RemoveAt(row.Index);
                break; 
        }
        using (SqlConnection sqcon = new SqlConnection(@"MY CONNECTION STRING")) 
        {
            SqlCommand Scmd = new SqlCommand();

            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                DataGridViewRow delrow = dataGridView1.Rows[i];
                if (delrow.Selected == true)
                {
                    dataGridView1.Rows.RemoveAt(i);
                    try
                    {
                        Scmd.CommandText = "DELETE FROM Technican WHERE ID=" + (i++) + "";
                        sqcon.Open(); //ADDED
                        int count = Scmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
            }
        }

    }

我应该使用什么来删除本地数据库和datagridview中的行?

2 个答案:

答案 0 :(得分:0)

试试这个, 从数据库中删除使用唯一列或Id列。

//Make datagridview cell[0] the unique column in your table.
try
{
    Scmd.CommandText = "DELETE FROM Technican WHERE ID='" + datagridview.rows[i].cell[0].value + "'";
    sqcon.Open(); //ADDED
    int count = Scmd.ExecuteNonQuery();
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

答案 1 :(得分:0)

我认为连接没有分配给命令对象。

SqlCommand Scmd = new SqlCommand();
Scmd.Connection = sqcon;

我也更喜欢使用 DataGridView.SelectedRows 而不是循环网格中的所有记录。

完整代码

    private void DeleteData_Click(object sender, EventArgs e)
    {
        var rowsToDelete = dataGridView1.SelectedRows;
        using (SqlConnection sqcon = new SqlConnection(@"MY CONNECTION STRING"))
        {
            SqlCommand Scmd = new SqlCommand();
            Scmd.Connection = sqcon;
            sqcon.Open(); //ADDED   
            foreach (DataGridViewRow row in rowsToDelete)
            {
                try
                {
                    Scmd.CommandText = "DELETE FROM Technican WHERE ID=" + row.Cells["Id"].Value.ToString() + "";
                    int count = Scmd.ExecuteNonQuery();

                    dataGridView1.Rows.Remove(row);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }

            }
            sqcon.Close();
        }
    }