![](/img/trans.png)
[英]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.