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

How can i delete data from a datagridview c#?

当我使用下面的代码时,它确实从 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 中删除行?

试试这个, 从数据库中删除使用唯一列或 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());
}

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

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