C# 如何使用LINQ C从datagridview在SQL Server中进行编辑#
我想从datagridview编辑数据库中字段的值 当我执行我的应用程序时,那一行是红色的,我想编辑数据库中的“bool_badge”值 例如:对于id=3,“bool_徽章”=1:当我单击“签出”按钮时,“bool_徽章”在我的数据库中应更改为0 我在C# 如何使用LINQ C从datagridview在SQL Server中进行编辑#,c#,sql-server,datagridview,C#,Sql Server,Datagridview,我想从datagridview编辑数据库中字段的值 当我执行我的应用程序时,那一行是红色的,我想编辑数据库中的“bool_badge”值 例如:对于id=3,“bool_徽章”=1:当我单击“签出”按钮时,“bool_徽章”在我的数据库中应更改为0 我在dataGridView1\u cellcontents中单击按钮签出的条件 代码: 所以,在这个条件之后,如果我想编辑我的数据库 我试过: if (dataGridView1.SelectedRows[0].DefaultCellStyle
dataGridView1\u cellcontents中单击按钮签出的条件
代码:
所以,在这个条件之后,如果我想编辑我的数据库
我试过:
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…并与我的数据库建立关系…但我不知道如何修复它
谢谢,因为行索引
是2,而您的ID
是3。您需要查看单元格值才能获取ID。将ID作为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
}
}
}
}
希望有帮助,我认为您的示例是错误的,例如:对于id=3,“bool_徽章”=1:当我单击“签出”按钮时,“bool_徽章”在我的数据库中应更改为1。不应该是0吗?哦,是的!抱歉,谢谢汉克斯,它有一个错误找不到名为id的列“”!!!它是如何找到fiel'id'的?是的,它在以下行中:int row=(int)this.dataGridView1.CurrentCell.OwningRow.Cells[“id”].Value;好的,让它成为单元格[0]
。
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
}
}
}
}