如何在 C# 中更新 DataGridView 单元格

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;
        }
    }
}

您的生活变得轻松:

  • 向您的项目添加一个新的 DataSet 文件,打开它,在 属性 网格中将其命名为 StudentDataSet
  • 右击,在surface中添加一个新的DataTable,命名为Students
  • 添加 StNo 列(使其成为 属性 网格中的整数)、StName、StAge (int)、StMark (int)
  • 右键单击 StNo 并将其设为主键
  • 保存
  • 切换到表单设计器,打开数据源面板(查看菜单..其他windows)
  • 将表示 table 的节点拖到窗体上。出现一个数据网格视图

现在更新标记所需的代码是:

var s = studentDataSet.Students.FindByStNo(123);
if(s!=null)
  s.StMark = 99;

是的,这就是您所需要的(另外您还需要加载 table 学生数据)


如果这些学生来自数据库,您可以通过不添加 DataTable 而是添加 TableAdapter 并设置将他们从数据库中拉出的数据库 connection/query 让您在第二步中更轻松数据库..