[英]How to update the target cell of a CurrentRow in DataGridView in C#?
[英]How to update DataGridView cell in c#
我在 c# WinForms 中有一个 DataGridView
在这个表单中,我用数据填充了一个大的 DataGridView,后面的过程需要很长时间。
无论如何,我的问题是我想根据标准更新该 DataGridView 中的一个单元格
DataGridView 有 4 列,StNo、StName、StAge、StMark。
我想搜索 StNo = 123 并将他们的 StMark 更新为 68
我尝试了以下但不起作用
grd1.Rows.Cast<DataGridViewRow>().Where(x => x.Cells["StNo"].Value.ToString() == "123")["StMark"] = 68;
怎么做?
DataGridView
是一个 winforms 控件,负责在 UI 中显示给定的记录,并通过不同的事件向底层记录提供用户输入。
因此,不要通过DataGridView
更新值 - 更新基础记录。
public class Student
{
public int Number { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int Mark { get; set; }
}
public class MyForm
{
public readonly BindingList<Student> _sutdents;
public MyForm()
{
_students = new BindingList<Student>();
myDataGridView.DataSource = _students;
}
private void AddStudentButton_Click(object sender, EventArgs args)
{
var student = new Student
{
Number = int.Parse(textboxNumber.Text),
Name = textboxName.Text,
Name = int.Parse(textboxAge.Text),
Name = int.Parse(textboxMark.Text),
};
_students.Add(student);
}
// After button click you should see that new student appears in the DataGridView
// Now you can update existing students from code without "touching" DataGridView
private void UpdateMarkButton_Click(object sender, EventArgs args)
{
var studentNumber = int.Parse(textboxNewMarkStudentNumber.Text);
var newMark = int.Parse(textboxNewMark.Text);
var student = _students.FirstOrDefault(s => s.Number = studentNumber);
if (student != null)
{
student.Mark = newMark;
}
}
}
你的生活,变得轻松:
现在更新标记所需的代码是:
var s = studentDataSet.Students.FindByStNo(123);
if(s!=null)
s.StMark = 99;
是的,这就是你所需要的(另外你需要用学生数据加载表)
如果这些学生来自数据库,您可以在第二步中通过不添加 DataTable 而是添加 TableAdapter 并设置将他们从数据库中拉出的数据库连接/查询来让您的生活更轻松。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.