【问题标题】:C# GridView rows added in wrong place?C# GridView 行添加到错误的位置?
【发布时间】:2018-10-31 20:19:34
【问题描述】:

我想在函数运行时向我的 GridView 添加行。

在调用添加行的函数之前,前一个函数总是存在 1 个“DATA”行。

添加我尝试使用的行:

int n = grid.Rows.Count;    
grid.Rows.Add("Step" + n.ToString());

我希望得到带有标签的行:

Data...    
Step1...
Step2...
Step3...
etc

相反,我得到:

Step1...
Step2...
Step3...
etc
Data...

(DATA行被推到最底部,所有行都添加到它上面) 我的错在哪里?

编辑: 我试过了:

int n = grid.Rows.Count;
DataGridViewRow row = new DataGridViewRow();         
grid.Rows.Insert(n, row);
grid.Rows[n].Cells[0].Value = "Step"+n.ToString();

但它会出错。

【问题讨论】:

  • 你可以使用grid.Rows.InsertAt(DataRow, index);
  • @DotNetDev InsertAt(DataRow, index); 函数似乎不存在?有Insert(rowIndex, DataGridViewRow)tho。

标签: c# gridview row add


【解决方案1】:

您可以创建 DataTable,然后将其显示在 GridView 上! 试试这个:

System.Data.DataTable table = new DataTable();
table.Columns.Add("col1", typeof(string));
table.Columns.Add("col2", typeof(string));
table.Columns.Add("col3", typeof(string));
...

这是创建行:

for (int i = 0; i < n - 1; i++)
        {
            DataRow dr = table.NewRow();
            if(i==0)
               {
                  dr[col1]="Data"
                  dr[col2]= ...
                  dr[col3]= ...
                  ...
               }
             if(i>0)
               {
                  // your code
               }
            table.Rows.Add(dr);
         }

将此表添加到 GridView:

DataView dv1 = new DataView(table);
dataGridView1.DataSource = dv1;

【讨论】:

  • 不确定它是否对我有用,因为从一开始就没有确定列数。确定程序何时完成从文件中解析数据并放入List&lt;string&gt; data(在单行中),我从中执行data.Count 以获取所需列的数量。从那时起,我想每次在代码中需要时在一行 GridView 中显示整个“数据”。
【解决方案2】:

使用Insert 添加记录,使用Count 作为最后一个位置

类似:

grid.Rows.Insert(grid.Rows.Count-1, row);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多