简体   繁体   English

无法在 C# 中以编程方式更改数据网格视图单元格的显示值

[英]Can't change the display value of Data Grid View cell programmatically in C#

I try to set the value of cell in my Data Grid View manually by code, however, when running there are nothing change.我尝试通过代码在我的数据网格视图中手动设置单元格的值,但是,在运行时没有任何变化。 I print the value of these cell to console and the cells ' value are set, but they're not display.我将这些单元格的值打印到控制台,单元格的值已设置,但未显示。

        `TheLoaiList = BUSTheLoai.Instance.GetAllTheLoai();
        TheLoaiGrid.DataSource = TheLoaiList;
        int i = 0;
        foreach (DataGridViewRow row in TheLoaiGrid.Rows)
        {
            row.Cells["SoTuaSach"].Value = "10";
            Console.WriteLine(row.Cells["SoTuaSach"].Value);
            i++;
        }`

Your code seems to be on the right track.您的代码似乎走在正确的轨道上。 Binding the TheLoaiGrid.DataSource to the TheLoaiList that's good because you can change what's in the DataGridView by changing TheLoaiList .TheLoaiGrid.DataSource TheLoaiList 因为您可以通过更改TheLoaiList来更改DataGridView中的内容。 The next step you might want to try is making the items in the list work the same way (using binding) so that when you do your loop, you can modify the data not the DataGridViewRow :您可能想要尝试的下一步是使列表中的项目以相同的方式工作(使用绑定),这样当您执行循环时,您可以修改数据而不是DataGridViewRow

foreach (TheLoai theLoai in TheLoaiList)
{
    theLoai.SoTuaSach = "10"; 
}

For this to work, it requires a small change to the class that represents your row items.为此,需要对代表您的行项目的类进行小的更改。 Suppose you defined TheLoaiList this way:假设您以这种方式定义TheLoaiList

BindingList<TheLoai> TheLoaiList { get; } = new BindingList<TheLoai>();

Then here's an example of how to automatically notify the DataGridView when a property changes using INotifyPropertyChanged :下面是一个示例,说明如何使用INotifyPropertyChanged在属性更改时自动通知DataGridView

// using System.Runtime.CompilerServices;
class TheLoai : INotifyPropertyChanged
{
    string _soTuaSach = string.Empty;
    public string SoTuaSach
    {
        get => _soTuaSach;
        set
        {
            if (!Equals(_soTuaSach, value))
            {
                _soTuaSach = value;
                OnPropertyChanged();
            }
        }
    }
    string _column2 = string.Empty;
    public string Column2
    {
        get => _column2;
        set
        {
            if (!Equals(_column2, value))
            {
                _column2 = value;
                OnPropertyChanged();
            }
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Here's a minimal working sample if you want to try this out.如果您想尝试一下,这里有一个最小的工作示例

截屏

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

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