【问题标题】:adding specific rows from datatable to datagridview?将数据表中的特定行添加到datagridview?
【发布时间】:2012-11-09 09:23:45
【问题描述】:

我有一个包含 1000 行的数据表,现在我想将此数据表中的第一个索引和最后一个索引之间的行范围添加到我的数据网格视图中。我该如何做到这一点?

数据表还包含有关我一直希望在 datagridview 中维护的列的信息。

PS: 第一个索引和最后一个索引是一些整数变量。 这是在使用 .net 平台的 c# 中。

【问题讨论】:

  • 你能贴出你试过的代码吗?

标签: c# .net datagridview


【解决方案1】:

假设你想使用第 100 到 200 行作为 DataSource,你可以使用Enumerable.Skip/Take

datagridView1.DataSource = table.AsEnumerable()
                                .Skip(100)
                                .Take(100)
                                .CopyToDatatable();

从 startIndex 到 endIndex 与 Enumerable.Where:

datagridView1.DataSource =  table.AsEnumerable()
                                 .Where((r, i) => i >= startIndex && i <= endIndex)
                                 .CopyToDatatable();

记得加using System.Linq;

【讨论】:

    【解决方案2】:

    您可以对数据使用过滤器来限制DataGridView 中显示的结果。做一些类似的事情

    DataTable tmpDt = GetDataTable();
    BindingSource source2 = new BindingSource();
    source2.DataSource = tmpDt;
    source2.Filter = "columnValue < 100 AND columnValue > 200";
    dataGridView2.DataSource = source2;
    

    这种方法的优点是过滤器不会破坏您的基础数据。您可以更改Filter,您可以更新DataGridView 中显示的数据。

    我希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      谷歌搜索给了我以下准备使用的文章,

      如何:将数据绑定到 Windows 窗体 DataGridView 控件 - http://msdn.microsoft.com/en-us/library/fbk67b6z.aspx

      http://www.switchonthecode.com/tutorials/csharp-tutorial-binding-a-datagridview-to-a-database

      【讨论】:

        【解决方案4】:

        这样试试

        DataRow[] rw = myDataTable.Select("#" + firstindex+ "# >= FirstIndexCol 
                                             AND SecondIndexCol <= #" + SecondIndex+ "#");
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-25
          • 2017-05-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多