简体   繁体   中英

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.

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. 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

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

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. Try calling datagridview1.Refresh() at the end of your event handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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