天天看點

當控件被資料綁定時,無法以程式設計方式向 DataGridView 的行集合中添加行

一、如果你的程式中,沒有如下代碼:

dataGridView1.DataSource = null;
dataGridView1.DataSource = JsonResult.Data;
           

說明你的 DataGridView沒有以程式設計方式綁定資料。這個時候你可以這樣添加新行:

int index=this.dataGridView1.Rows.Add();
this.dataGridView1.Rows[index].Cells[0].Value = "XXX"; 
this.dataGridView1.Rows[index].Cells[1].Value = "XXX"; 
this.dataGridView1.Rows[index].Cells[2].Value = "XXX";
           

利用dataGridView1.Rows.Add()事件為DataGridView控件增加新的行,該函數傳回添加新行的索引号,即新行的行号。

二、如果你的程式報出異常資訊和标題一樣。。。。。。:那解決辦法如下:

理清思路,你的dataGridView1綁定的資料集合是什麼。然後添加新行的時候要先集合添加,在顯示在dataGridView1中。比如題主的集合:

public class JsonRes
    {
        public List<Count> Data { get; set; } 
    }
    public class Count
    {
        public string Title { get; set; }
        public string Logo { get; set; }
        public string Type { get; set; }
        public string Date { get; set; }
        public string IsCheck { get; set; }
    }
           

在添加新行的事件中寫:

Count count = new Count();
            count.Title ="XXX";
            count.Logo = "XXX";
            count.Type = "XXX";
            count.Date = "XXX";
            count.IsCheck = "XXX";
            jsonResult.Data.Add(count);
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = jsonResult.Data;
           

這種辦法才是最實用的。。。。。純手敲。。。。。

偶遇問題。及時記錄。。。。