删除行并保存DataGridView



我还没有在C#表单应用程序中对DataGridViews做太多工作,所以我相信我的方法是新手。任何帮助都会很棒!

我的表单正在显示数据库的DataGridView,我想让用户可以选择删除所选的特定行,然后保存更改。

这是我的代码:

    private void btnDeleteCustomer_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
        {
            dataGridView1.Rows.RemoveAt(item.Index);
            dataGridView1.SelectAll();
        }
    }
    private void btnSelectAll_Click(object sender, EventArgs e)
    {
        dataGridView1.SelectAll();
    }

我正试图删除所选行,然后选择所有剩余行,然后单击一个按钮保存所选的剩余行。我相信有更好的方法可以做到这一点,但我找不到有效的解决方案。谢谢

我看没有太大的区别,但你可以用不同的方式删除行。你可能想考虑使用扩展方法来轻松扩展数据网格视图功能,例如:

public static class DataGridViewExtensions
    {
        public static void DeleteSelectedRows(this DataGridView dgv)
        {
            foreach (DataGridViewRow row in dgv.SelectedRows)
                dgv.Rows.Remove(row);
        }
    }

你可以简单地像一样调用这个函数

dataGridView1.DeleteSelectedRows();
        Int32 rowToDelete = dataGridView1.Rows.GetFirstRow(DataGridViewElementStates.Selected);
        if (rowToDelete > -1)
        {
          dataGridView1.Rows.RemoveAt(rowToDelete);
          dataGridView1.Invalidate();
          string lastName = (string)dataGridView1.Rows[rowToDelete].Cells[0].Value;
          string firstName = (string)dataGridView1.Rows[rowToDelete].Cells[1].Value;
          string email = (string)dataGridView1.Rows[rowToDelete].Cells[2].Value;
          string phoneNumber = (string)dataGridView1.Rows[rowToDelete].Cells[3].Value;
          string address = (string)dataGridView1.Rows[rowToDelete].Cells[4].Value;
          string instagram = (string)dataGridView1.Rows[rowToDelete].Cells[5].Value;
          string carMake = (string)dataGridView1.Rows[rowToDelete].Cells[6].Value;
          string carModel = (string)dataGridView1.Rows[rowToDelete].Cells[7].Value;
          string additionalNotes = (string)dataGridView1.Rows[rowToDelete].Cells[8].Value;
          SqlConnection CustomerInfo = new SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Cory\Desktop\DeluxWrapsWindows\DeluxWrapsWindows\DeluxWraps.mdf;Integrated Security=True;User Instance=True");
          {
             SqlCommand xp = new SqlCommand("DELETE FROM CustomerInfo WHERE LastName='" + lastName + "' AND FirstName='" + firstName + "'");
             CustomerInfo.Open();
             xp.ExecuteNonQuery();
             CustomerInfo.Close();
          }
        }

相关内容

  • 没有找到相关文章

最新更新