簡體   English   中英

如何向未綁定的DataGridView添加行?

[英]How to add a row to a unbound DataGridView?

我在C#中有一個DataGridView ,我想以編程方式添加行。 沒有綁定到網格的數據但是當我調用dataGrid.Rows.Add(); 它拋出一個System.InvalidOperationException

我瀏覽了整個互聯網,我發現這個問題對於有數據綁定的人來說。 我希望從代碼中完全控制網格。

有人可以幫我這個嗎?

不確定它是否有所作為,但我使用.Net framework 3.5。

假設您已經使用設計器或代碼創建了列,您可以執行以下操作:

var row = (DataGridViewRow)myDataGridView.RowTemplate.Clone();
row.CreateCells(myDataGridView, "I'm Cell 1", "I'm Cell 2", "etc.");
myDataGridView.Rows.Add(row);

理想情況下,如果要添加許多行,則需要預先創建一個行數組並調用AddRange(rows); 代替。

例:

void PopulateGrid()
{
    //Consider Suspend-Resume Layout, YMMV.
    var rows = myData.Select(data => CreateRow(data)).ToArray();
    myDataGridView.Rows.AddRange(rows);
}

DataGridViewRow CreateRow(MyData data)
{
    var row = (DataGridViewRow)myDataGridView.RowTemplate.Clone();
    row.CreateCells(myDataGridView, data.Text, data.Date, date.Value);
    return row;
}

我能給出的最簡單的例子是:

/// <summary>
/// Shows example usage of Add method on Rows.
/// </summary>
void M()
{
    //
    // n is the new index. The cells must also be accessed by an index.
    // In this example, there are four cells in each row.
    //
    int n = dataGridView1.Rows.Add();

    dataGridView1.Rows[n].Cells[0].Value = title;
    dataGridView1.Rows[n].Cells[1].Value = dateTimeNow;

    //
    // The second cell is a date cell, use typeof(DateTime).
    //
    dataGridView1.Rows[n].Cells[1].ValueType = typeof(DateTime);
    dataGridView1.Rows[n].Cells[2].Value = wordCount;
}

我通常會選擇其他人提供的答案,但事實並非如此,因為答案並不真正有用。

正如我所說的“dataGridView1.Rows.Add();” 拋出異常,AddRange也是如此。
經過大量檢查后我找到了答案。 顯然.Net不喜歡它,如果我添加很多行/秒(大約30)。
我通過網絡接收我的行,所以我創建了一個行池,每秒我都會更新datagridview中的行。
這似乎修復了未顯示的行和異常。

無論如何,謝謝你的輸入!

暫無
暫無

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

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