![](/img/trans.png)
[英]C# Visual Studio: How do I update a DB from Edit with DataGridView using LINQ?
[英]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 獲取為RowIndex
是RowIndex
。 如果 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.