[英]Insert datagridview column values into an Array c#
In my form I have this DataGridView (grid1), filled from a sqllite database. 在我的表单中,我有这个DataGridView(grid1),它是从sqllite数据库填充的。
I want select the column with the name "cap" and insert the column's values into an array. 我想选择名称为“ cap”的列,并将该列的值插入到数组中。 How can I do?
我能怎么做?
I tryed to do this way (from an old answer here in the site) but it gives me error of "out of bounded matrix" 我试图这样做(从站点的旧答案),但是它给了我“超出界矩阵”的错误
int[] wareCap = new int[grid1.Rows.Count];
...
//How I filled my dgv, if this can help
var context = new ForliCesenaEntities2();
BindingSource bi1 = new BindingSource();
bi1.DataSource = context.warehouses.ToList();
grid1.DataSource = bi1;
grid1.Refresh();
//How I try to insert the values into int[] wareCap
for (int i = 0; i<(grid1.Rows.Count-1); i++)
wareCap[i] = Convert.ToInt16(grid1.Rows[i].Cells[1].Value);
Thanks in advice 谢谢建议
First you gridview has to be filled with values, then: 首先,gridview必须填充值,然后:
List<int> intValues = new List<int>();
foreach (DataGridViewRow row in grid.Rows)
{
intValues.Add(int.Parse(row.Cells["cap"].Value.ToString()));
}
int[] array = intValues.ToArray();
should do the trick. 应该可以。
Alternatively, you could use LINQ. 或者,您可以使用LINQ。
int[] intArray = dataGridView1.Rows
.Cast<DataGridViewRow>()
.Select(row => int.Parse(row.Cells["cap"].Value.ToString())).ToArray();
UPDATE: 更新:
The above solution might crash if the DataGridView's AllowUserToAddRows property is set to true. 如果DataGridView的AllowUserToAddRows属性设置为true,则上述解决方案可能会崩溃。 Because in that case your last row is the row for entering a new record, the Value is null, so invoking the ToString method on it causes a NullReferenceException.
因为在这种情况下,您的最后一行是用于输入新记录的行,所以Value为null,因此对其调用ToString方法将导致NullReferenceException。
I see two possibilities: 我看到两种可能性:
Check if the row is the row for entering a new record: 检查该行是否是用于输入新记录的行:
int[] intArray = dataGridView1.Rows
.Cast<DataGridViewRow>()
.Where(row => !row.IsNewRow)
.Select(row => Convert.ToInt32(row.Cells["cap"].Value.ToString())).ToArray();
You already got all your values in a List, because you do sth. 您已经在列表中获得了所有值,因为您确实这样做了。 like this:
像这样:
bi1.DataSource = context.warehouses.ToList();
You can easily store this in a reference: 您可以轻松地将其存储在参考中:
var values = context.warehouses.ToList();
bi1.DataSource = values;
Your Grid is build based on Objekts in this List. 您的网格是基于此列表中的对象构建的。 So this should build your array:
因此,这应该构建您的数组:
int[] array = new int[values.Count];
int counter = 0;
foreach (var object in values)
{
array[counter++] = object.CAP;
}
int[] wareCap = new int[grid1.Rows.Count];
foreach(DataGridViewRow row in grid1.Rows)
{
wareCap.Add(Convert.ToInt32(cell["cap"].Value.ToString()));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.