C# 手动在 datagridview 上添加行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13362971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:19:23  来源:igfitidea点击:

Adding rows on datagridview manually

c#winforms

提问by user1647667

I've inserted a checkbox column and textbox column on the datagridview. how can add rows manually on the textbox column.

我在 datagridview 上插入了一个复选框列和文本框列。如何在文本框列上手动添加行。

It should be like this:

应该是这样的:

checkbox | textbox
............................
checkbox | item1
checkbox | item2
checkbox | item3
checkbox | item4

Here is the code for checkbox and textbox on datagridview

这是 datagridview 上复选框和文本框的代码

public void loadgrid()
{
    DataGridViewCheckBoxColumn checkboxColumn = new DataGridViewCheckBoxColumn();
    CheckBox chk = new CheckBox();
    checkboxColumn.Width = 25;
    dataGridView1.Columns.Add(checkboxColumn);

    DataGridViewTextBoxColumn textboxcolumn = new DataGridViewTextBoxColumn();
    TextBox txt = new TextBox();
    textboxcolumn.Width = 150;
    dataGridView1.Columns.Add(textboxcolumn);     
}

采纳答案by Nikola Davidovic

You can pass an object array that contains the values which should be inserted into the DataGridViewin the order how the columns are added. For instance you could use this:

您可以传递一个对象数组,该数组包含应按照DataGridView添加列的顺序插入的值。例如你可以使用这个:

dataGridView1.Rows.Add(new object[] { true, "string1" });
dataGridView1.Rows.Add(new object[] { false, "string2" });

And you can build object array from whatever you want, just be sure to match the type (i.e. use bool for checkedColumn)

并且您可以从任何您想要的对象构建对象数组,只需确保匹配类型(即对checkedColumn 使用bool)

回答by CloudyMarble

You can use the Rows collection to manually populate a DataGridView control instead of binding it to a data source.

您可以使用 Rows 集合手动填充 DataGridView 控件,而不是将其绑定到数据源。

this.dataGridView1.Rows.Add("five", "six", "seven", "eight");
this.dataGridView1.Rows.Insert(0, "one", "two", "three", "four");

Take a look at the documentation

看一下文档

And you can do something like this too:

你也可以做这样的事情:

DataGridViewRow row = (DataGridViewRow)yourDataGridView.Rows[0].Clone();
row.Cells["Column2"].Value = "XYZ";
row.Cells["Column6"].Value = 50.2;
yourDataGridView.Rows.Add(row);

See this answer

看到这个答案