簡體   English   中英

如何使用 LINQ C# 從 datagridview 在 SQL Server 中進行編輯

[英]How edit in SQL Server from datagridview with LINQ C#

我想從我的 datagridview 編輯我的數據庫中的字段值。

當我執行我的應用程序時,顏色為紅色的行,我想編輯我的數據庫中的 'bool_badge' 值。

例如:對於 id=3, 'bool_badge'=1 :當我點擊按鈕 Check-Out 時,'bool_badge' 應該在我的數據庫中更改為 0

在此處輸入圖片說明

我在dataGridView1_CellContentClick條件中有按鈕dataGridView1_CellContentClick

在此處輸入圖片說明

代碼:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (dataGridView1.SelectedRows[0].DefaultCellStyle.BackColor == Color.Red)
    {
        if (MessageBox.Show("Check-out?",
                            "Message de confirmation",
                            MessageBoxButtons.YesNo) == DialogResult.Yes)

所以,在這個條件之后,如果我想編輯我的數據庫......

我試過:

if (dataGridView1.SelectedRows[0].DefaultCellStyle.BackColor == Color.Red)
{
    int row = this.dataGridView1.CurrentCell.RowIndex;

    if (MessageBox.Show("Check-out?",
                        "Message de confirmation",
                        MessageBoxButtons.YesNo) == DialogResult.Yes)
    {  
        using (checkinentrepriseEntities2 context = new checkinentrepriseEntities2())
        {
            badge badge = new badge();                     

            badge badverif = context.badge.FirstOrDefault(x => x.id == row);

            if (badverif != null)
            {
                badverif.bool_badge = 0;
            }

但我知道這個代碼是行不通的

我必須找到所選行的確切 ID...並與我的數據庫建立關系...但我不知道如何修復它?

謝謝

因為RowIndex是 2 而你的ID是 3。你需要查看單元格值來獲取 ID。 將 ID 獲取為RowIndexRowIndex 如果 ID 像 1,2,3,5,6,7 會怎樣? 你應該得到這樣的ID ,你應該使用SaveChanges()來更新值

if (dataGridView1.SelectedRows[0].DefaultCellStyle.BackColor == Color.Red)
            {
                int row = (int)this.dataGridView1.CurrentCell.OwningRow.Cells["id"].Value; 
               // selected cells owning rows ID cell's value will give the ID
                if (MessageBox.Show("Check-out?",
                                  "Message de confirmation",
                                  MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    using (checkinentrepriseEntities2 context = new checkinentrepriseEntities2())
                    {
                        badge badg = new badge();

                        badge badverif = context.badge.FirstOrDefault(x => x.id == row);

                        if (badverif != null)
                        {
                            badverif.bool_badge = 0;
                            context.SaveChanges(); // and savechanges after set update value
                        }
                    }
                }
            }

希望有所幫助,

暫無
暫無

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

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