繁体   English   中英

如何更新 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
  • 右键单击,向表面添加一个新的 DataTable,将其命名为 Students
  • 添加 StNo 列(使其成为属性网格中的 int)、StName、StAge (int)、StMark (int)
  • 右键单击 StNo 并将其设为主键
  • 节省
  • 切换到表单设计器,打开数据源面板(查看菜单..其他窗口)
  • 将代表表格的节点拖到表单上。 出现一个datagridview

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

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

是的,这就是你所需要的(另外你需要用学生数据加载表)


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM