dataInfo = new DeviceManage.设备采购(); foreach (DataGridViewRow row in dataGridView1.Rows) { if (row.Selected == true) { if (isadmin == "1") { if (row.Cells[0].Value == null) { dataInfo.buy_no = cgdh.Text = dataGridView1.Rows[i].Cells[2].Value.ToString(); dataInfo.login_no = yhbh.Text = dataGridView1.Rows[i].Cells[3].Value.ToString(); dataInfo.dev_name = xbmc.Text = dataGridView1.Rows[i].Cells[4].Value.ToString(); dataInfo.dev_model = xbxh.Text = dataGridView1.Rows[i].Cells[5].Value.ToString(); dataInfo.gys_name = gys.Text = dataGridView1.Rows[i].Cells[6].Value.ToString(); dataInfo.buy_date = dateTimePicker1.Text = dataGridView1.Rows[i].Cells[7].Value.ToString(); dataInfo.price = dj.Text = dataGridView1.Rows[i].Cells[8].Value.ToString(); dataInfo.num = sl.Text = dataGridView1.Rows[i].Cells[9].Value.ToString(); }
时间: 2024-01-21 12:04:46 浏览: 27
将上述代码中的 `for` 循环改为 `foreach` 循环,并将代码中的索引变量 `i` 替换为 `row.Index`,可以使用以下代码:
```csharp
dataInfo = new DeviceManage.设备采购();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Selected == true)
{
if (isadmin == "1")
{
if (row.Cells[0].Value == null)
{
dataInfo.buy_no = cgdh.Text = row.Cells[2].Value.ToString();
dataInfo.login_no = yhbh.Text = row.Cells[3].Value.ToString();
dataInfo.dev_name = xbmc.Text = row.Cells[4].Value.ToString();
dataInfo.dev_model = xbxh.Text = row.Cells[5].Value.ToString();
dataInfo.gys_name = gys.Text = row.Cells[6].Value.ToString();
dataInfo.buy_date = dateTimePicker1.Text = row.Cells[7].Value.ToString();
dataInfo.price = dj.Text = row.Cells[8].Value.ToString();
dataInfo.num = sl.Text = row.Cells[9].Value.ToString();
}
}
}
}
```
在 `foreach` 循环中,`row` 直接表示集合中的每个元素,可以直接使用 `row.Cells[0]` 访问该行中的第一列单元格。使用 `row.Index` 可以获取当前行的索引。注意,`foreach` 循环中的变量是只读的,不能修改它们的值,因此需要使用 `row.Index` 来代替原来的索引变量 `i`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)