dataInfo.sp_no = bfdh.Text = dataGridView1.Rows[i].Cells[2].Value.ToString(); 报错
时间: 2024-05-18 10:12:12 浏览: 13
这段代码的错误可能是多种原因导致的,需要进一步分析。根据报错信息,可能是其中某个属性或方法没有正确调用或声明。建议你先检查以下几个方面:
1. `dataInfo` 是否已经实例化。
2. `bfdh` 是否已经实例化。
3. `dataGridView1` 是否已经正确绑定数据。
4. `i` 是否超出了 `dataGridView1` 的行数范围。
5. `Cells[2]` 是否存在于 `dataGridView1` 的每一行中。
6. `Value` 是否存在于 `Cells[2]` 对象中。
你可以根据报错信息进一步调试,或者将代码片段及报错信息分享出来,便于更好地帮助你解决问题。
相关问题
dataInfo = new DeviceManage.设备报废(); for (int i = 0; i < dataGridView1.Rows.Count; i++) { if (dataGridView1.Rows[i].Selected == true) { if (isadmin == "1") { if (dataGridView1.Rows[i].Cells[0].Value == null) { dataInfo.sp_no = bfdh.Text = dataGridView1.Rows[i].Cells[2].Value.ToString(); dataInfo.login_no = yhbh.Text = dataGridView1.Rows[i].Cells[3].Value.ToString(); dataInfo.dev_no = sbbh.Text = dataGridView1.Rows[i].Cells[4].Value.ToString(); dataInfo.sp_why = bfyy.Text = dataGridView1.Rows[i].Cells[5].Value.ToString(); dataInfo.remark = bz.Text = dataGridView1.Rows[i].Cells[6].Value.ToString(); } 改成foreach
将上面的代码改为foreach循环,可以按照如下方式实现:
```
dataInfo = new DeviceManage.设备报废();
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
if (isadmin == "1")
{
if (row.Cells[0].Value == null)
{
dataInfo.sp_no = bfdh.Text = row.Cells[2].Value.ToString();
dataInfo.login_no = yhbh.Text = row.Cells[3].Value.ToString();
dataInfo.dev_no = sbbh.Text = row.Cells[4].Value.ToString();
dataInfo.sp_why = bfyy.Text = row.Cells[5].Value.ToString();
dataInfo.remark = bz.Text = row.Cells[6].Value.ToString();
}
}
}
```
这样就可以遍历选中的DataGridView行,将每一行的数据存入对应的变量中。
for (int i = 0; i < dataGridView1.Rows.Count; i++) { if (dataGridView1.Rows[i].Selected == true) { dataInfo.ft_no = bxdh.Text = dataGridView1.Rows[i].Cells[0].Value.ToString(); dataInfo.login_no = yhbh.Text = dataGridView1.Rows[i].Cells[1].Value.ToString(); dataInfo.dev_no = xbbh.Text = dataGridView1.Rows[i].Cells[2].Value.ToString(); dataInfo.ftwhy = gzyy.Text = dataGridView1.Rows[i].Cells[3].Value.ToString(); dataInfo.ftstatus = gzztms.Text = dataGridView1.Rows[i].Cells[4].Value.ToString(); dataInfo.remark = bz.Text = dataGridView1.Rows[i].Cells[5].Value.ToString(); } }改写dpreach
可以这样改写:
```
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
dataInfo = new DeviceManage.故障管理();
dataInfo.ft_no = bxdh.Text = row.Cells[0].Value.ToString();
dataInfo.login_no = yhbh.Text = row.Cells[1].Value.ToString();
dataInfo.dev_no = xbbh.Text = row.Cells[2].Value.ToString();
dataInfo.ftwhy = gzyy.Text = row.Cells[3].Value.ToString();
dataInfo.ftstatus = gzztms.Text = row.Cells[4].Value.ToString();
dataInfo.remark = bz.Text = row.Cells[5].Value.ToString();
}
```
这样,遍历选中行的过程中,每次都会新创建一个 `dataInfo` 对象,并将选中行的对应值赋值给它。同时,使用 `foreach` 遍历选中行的集合,可以避免遍历所有行,提高效率。