【问题标题】:Can I add DataTable in DataGridView without using DataSource property我可以在不使用 DataSource 属性的情况下在 DataGridView 中添加 DataTable
【发布时间】:2013-08-21 14:51:35
【问题描述】:

这是将 DataTable 复制到 DataGridView 中的方法,该方法不起作用,此方法只能在 DataGridView 中添加列和 empty 行。任何人都可以在不使用 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);
            }
        }
    }

【问题讨论】:

  • 你为什么不想使用DataSource属性?
  • @gunr2171 因为我想在 DataGridView 上进行一些操作,但 DataSource 限制我这样做..
  • 不太清楚你为什么不想使用DataSource 属性。目前,您正在添加每一行的 ToString 实现,而不是您应该为该行添加来自每一列的数据数组。您可以在this question 看到通过代码在网格视图中添加行
  • @AnkushMadankar,我不明白DataSource 会如何限制你。请记住,您可以传入自定义class,而不仅仅是DataTable,作为数据。可以先格式化类中的数据,再插入类。

标签: c# datagridview datatable


【解决方案1】:

您正在尝试将 DataRow 添加到 DataGridView 而不是添加 DataGridViewRow

看看 visualstudio 的智能告诉您有关 DataGridView.Rows.Add() 方法的内容。其中有 4 个:

  • Add() - 向 DataGridView 添加一个空行

  • Add(DataGridViewRow) - 添加新行(这是您需要的)

  • Add(count) - 将 [count] 个空行添加到 DataGridView

  • Add(object[]) 添加新行并用值填充它(您也可以使用它)

您当前使用的是最后一个:Add(object[])。编译器不会抱怨,因为它将您传递给它的 DataGridViewRow 视为一个对象数组,其中只有一个对象。显然不是你想要的。

这里是相关问题:https://stackoverflow.com/a/9094325/891715

【讨论】:

    【解决方案2】:

    通过在 DataGridView 中添加行之前添加以下行,我的问题得到解决。

       object[] _items = _row.ItemArray;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 1970-01-01
      • 2018-10-03
      • 2018-04-30
      • 1970-01-01
      • 2011-12-09
      • 2011-05-25
      相关资源
      最近更新 更多