簡體   English   中英

在DataGridView中單擊按鈕時,為什么不顯示其他行?

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

這是我的代碼:

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; }
    }
}

我希望每次按下按鈕時,都會向dataridview添加新行。

我不確定為什么這種情況不會發生,我也不知道如何實現。 任何幫助深表感謝。

您需要發出事件以重繪datagrid。 接下來,如果您的數據源不大,最簡單的方法是:

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

如果您的集合太大,則最好將容器從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;
    }

在代碼中,您可以像使用List一樣使用ObservableCollection,但是它將告訴您的數據網格有關更改apples容器中項目的信息

像許多UI框架一樣,Forms不會自動重繪自身-因此必須(通常是明確地)告知何時數據已更改並且需要刷新。 嘗試在事件處理程序的末尾調用datagridview1.Refresh()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM