簡體   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