簡體   English   中英

C#DataGridView插入和刪除選定的行

[英]C# DataGridView Insert and Delete selected row

我已將SQL數據庫連接到Visual Studio中的C#項目。 在comboBox中,我從數據庫中獲取表的名稱,當我單擊按鈕時,它會在DataGridView中顯示當前表的內容。 我想知道如何從選定的行中保存/刪除日期?

附言:這些表具有不同的名稱和不同的列,我需要一些保存/刪除按鈕才能對所有表起作用

您可以將按鈕添加到DataGridView並使用CellContentClick事件。 這就是您添加按鈕的方式:

DataGridViewButtonColumn editButton = new DataGridViewButtonColumn();
editButton.HeaderText = "Update";
editButton.Text = "Update";
editButton.UseColumnTextForButtonValue = true;
editButton.Width = 80;
dbgViewObj.Columns.Add(editButton);//dbgViewObj is your datagridview control
DataGridViewButtonColumn deleteButton = new DataGridViewButtonColumn();
deleteButton.HeaderText = "Delete";
deleteButton.Text = "Delete";
deleteButton.UseColumnTextForButtonValue = true;
deleteButton.Width = 80;
dbgViewObj.Columns.Add(deleteButton);

然后,您的CellContentClick可能類似於以下內容:

private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
     int check = 0;
     int currentRow = e.RowIndex;

     if (e.RowIndex == -1 || e.ColumnIndex == -1)
     {
         return;
     }

     if (dgv.Columns[e.ColumnIndex].HeaderText == "Delete" && currentRow >= 0) 
     {
          //do your delete stuff (query a delete query)
     }
     if (dgv.Columns[e.ColumnIndex].HeaderText == "Update" && currentRow >= 0) 
     {
         //do your update stuff (query an update statement)
     }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM