简体   繁体   English

在DataGridView中单击按钮时,为什么不显示其他行?

[英]How come additional rows aren't being shown when button is clicked in DataGridView?

This is my code: 这是我的代码:

namespace UpdateDataGridView
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        List<Apple> apples = new List<Apple>();

        private void button1_Click(object sender, EventArgs e)
        {
            apples.Add(new Apple { Color = "Red"});
            dataGridView1.DataSource = apples;
        }
    }
    public class Apple
    {
        public string Color { get; set; }
    }
}

I am expecting a new row to be added to the dataridview every time the button is pressed. 我希望每次按下按钮时,都会向dataridview添加新行。

I am not sure why this is not happening and I don't know how to achieve this. 我不确定为什么这种情况不会发生,我也不知道如何实现。 Any help is much appreciated. 任何帮助深表感谢。

You need to emit event for datagrid redraw. 您需要发出事件以重绘datagrid。 The simplest way, if your DataSource isn't big is next: 接下来,如果您的数据源不大,最简单的方法是:

private void button1_Click(object sender, EventArgs e)
    {
        apples.Add(new Apple { Color = "Red"});
        dataGridView1.DataSource = null;
        dataGridView1.DataSource = apples;
    }

If your collection is too big, you'd better to change your container from List to ObservableCollection 如果您的集合太大,则最好将容器从List更改为ObservableCollection

ObservableCollection<Apple> apples = new ObservableCollection<Apple>();

    private void button1_Click(object sender, EventArgs e)
    {
        apples.Add(new Apple { Color = "Red"});
        dataGridView1.DataSource = apples;
    }

In your code, you can use ObservableCollection just like List, but it will tell your datagrid about changing items in your apples container 在代码中,您可以像使用List一样使用ObservableCollection,但是它将告诉您的数据网格有关更改apples容器中项目的信息

Like many UI frameworks, Forms does not automatically redraw itself - it therefore must be told (often explicitly) when data has been changed and that it needs to refresh. 像许多UI框架一样,Forms不会自动重绘自身-因此必须(通常是明确地)告知何时数据已更改并且需要刷新。 Try calling datagridview1.Refresh() at the end of your event handler. 尝试在事件处理程序的末尾调用datagridview1.Refresh()

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

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