将DataTable行添加到DataGridView而不绑定 [英] Add DataTable Row to DataGridView without binding
问题描述
我有一个预定义的DataGridView,我需要从DataTable添加行,而不需要数据绑定。然而,我试图以编程方式使用 DataGridView.Rows.Add()
方法,我不知道DataTable的列名称。 DataTable中的列与DataGridView的顺序相同,但是如何将它们添加到DataGridView中而不知道列名?
I have a predefined DataGridView that I need to add rows to from a DataTable without data binding. I am trying to use the DataGridView.Rows.Add()
method programmatically however, I do not know the column names of the DataTable. The columns in the DataTable are in the same order as the DataGridView but how do I add them to the DataGridView without knowing the column names?
推荐答案
说你的DataGridView存在但没有列。你可以这样做:
Say your DataGridView exists but has no columns. You can do this:
foreach (DataColumn dc in yourDataTable.Columns) {
yourDataGridView.Columns.Add(new DataGridViewTextBoxColumn());
}
然后添加行数据:
foreach(DataRow dr in yourDataTable.Rows) {
yourDataGridView.Rows.Add(dr.ItemArray);
}
现在,如果默认的文本框列不够,您可能必须使用不同的单元格模板创建列。
Now, if the default textbox column isn't sufficient, you might have to create a column with a different cell template.
这篇关于将DataTable行添加到DataGridView而不绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!