简体   繁体   English

如何将数据从列表插入到数据网格视图的列

[英]How to insert data from list to a column of data grid view

I have a data grid view (dataGridViewPorosity) with 2 columns and I want to insert data from a list (Porosity) to one of this columns, but the exception is: Index was out of range. 我有一个包含2列的数据网格视图(dataGridViewPorosity),我想将列表(Porosity)中的数据插入到其中一列中,但是例外是:索引超出范围。 most be non-negative and less than the size of the collection. 大多数都是非负数,并且小于集合的大小。

here is my code: 这是我的代码:

        var source = new BindingSource
        {
        DataSource = Porosity
        };
        for (int i = 0; i < source.Count; i++)
        {
             dataGridViewPorosity[1,i].Value = source[i];
        }

I saw the similar questions but cannot fix the problem 我看到了类似的问题,但无法解决问题

The DataGridView control works differently from the other tables you might know (or arrays). DataGridView控件的工作方式与您可能知道的其他表(或数组)不同。 You need to choose the row and cell. 您需要选择行和单元格。 The cell is basically the column. 单元格基本上是列。

dataGridViewPorosity.Rows[rowNumber].Cells[cellNumber].Value = source[i];

I assume you want to use the second cell and the row with the i value. 我假设您要使用第二个单元格和具有i值的行。 You can do it just like that: 您可以这样做:

dataGridViewPorosity.Rows[i].Cells[1].Value = source[i];

Good luck! 祝好运!

EDIT : Try to create new rows, like so: 编辑尝试创建新行,如下所示:

int rownum = dataGridViewPorosity.Rows.Add();

And then use the rownum as the row number you would like to insert your data to. 然后将rownum用作要插入数据的行号。

dataGridViewPorosity.Rows[rownum].Cells[1].Value = source[i];

Of course, these must be in the for loop. 当然,这些必须在for循环中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM