[英]Can I add DataTable in DataGridView without using DataSource property
Here is method which copy DataTable into DataGridView which is not not working, this method only able to add columns and empty rows in DataGridView. 这是将DataTable复制到不起作用的DataGridView的方法,该方法只能在DataGridView中添加列和空行。 Can any one suggest me solution for this without using DataSource property of DataGridView? 在不使用DataGridView的DataSource属性的情况下,有人可以建议我解决方案吗?
public void CopyDataTableInDataGridView(DataTable table, DataGridView gdv)
{
if (gdv.Rows.Count > 0)
gdv.Rows.Clear();
if (table != null && table.Rows.Count > 0)
{
foreach (DataColumn _colm in table.Columns)
{
DataGridViewColumn _col;
if (_colm.GetType() == typeof(bool))
_col = new DataGridViewCheckBoxColumn();
else
_col = new DataGridViewTextBoxColumn();
_col.Name = _colm.ColumnName;
_col.HeaderText = string.Concat(_colm.ColumnName.Select(x => Char.IsUpper(x) ? " " + x : x.ToString())).TrimStart(' ');
gdv.Columns.Add(_col);
}
foreach (DataRow _row in table.Select())
{
//Rows getting added in dgv but not data
// By adding following line in Code my problem get solved
//object[] _items = _row.ItemArray;
gdv.Rows.Add(_row);
}
}
}
You are trying to add a DataRow to DataGridView instead of adding DataGridViewRow 您正在尝试将DataRow添加到DataGridView,而不是添加DataGridViewRow
Look at what visualstudio's intelisence is telling you about DataGridView.Rows.Add() methods. 查看visualstudio的智能告诉您有关DataGridView.Rows.Add()方法的信息。 There are 4 of them: 其中有4个:
Add() - adds an empty row to DataGridView Add()-向DataGridView添加一个空行
Add(DataGridViewRow) - adds new row (this is what you need) Add(DataGridViewRow)-添加新行(这是您需要的)
Add(count) - adds [count] of empty rows to DataGridView Add(count)-将[count]个空行添加到DataGridView
Add(object[]) adds new row and populates it with values (you can also use this) Add(object [])添加新行并在其中填充值(您也可以使用此行)
you are currently using the last one: Add(object[]). 您当前正在使用最后一个:Add(object [])。 compiler doesn't complain because it's treating DataGridViewRow you passed to it as an array of objects with only one object in it. 编译器不会抱怨,因为它会将您传递给它的DataGridViewRow视为对象数组,其中仅包含一个对象。 Obviously not what you want. 显然不是您想要的。
here is related question: https://stackoverflow.com/a/9094325/891715 这是相关的问题: https : //stackoverflow.com/a/9094325/891715
通过在DataGridView中添加行之前添加以下行,我的问题得到解决。
object[] _items = _row.ItemArray;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.