dataInfo = new 用户基本信息(); for (int i = 0; i < dataGridView1.Rows.Count; i++) { if (dataGridView1.Rows[i].Selected == true) { dataInfo.No = yhbh.Text = dataGridView1.Rows[i].Cells[0].Value.ToString(); dataInfo.Name = yhmc.Text = dataGridView1.Rows[i].Cells[1].Value.ToString(); dataInfo.Password = yhmm.Text = dataGridView1.Rows[i].Cells[2].Value.ToString(); dataInfo.Dept = bm.Text = dataGridView1.Rows[i].Cells[3].Value.ToString(); dataInfo.Nation = zw.Text = dataGridView1.Rows[i].Cells[5].Value.ToString(); dataInfo.Job = textBox11.Text = dataGridView1.Rows[i].Cells[4].Value.ToString(); dataInfo.Birthday = dateTimePicker1.Text = dataGridView1.Rows[i].Cells[6].Value.ToString(); dataInfo.Phone = dh.Text = dataGridView1.Rows[i].Cells[7].Value.ToString(); dataInfo.Mail = yx.Text = dataGridView1.Rows[i].Cells[8].Value.ToString(); } }转化成不一样的代码
时间: 2024-01-25 18:01:49 浏览: 67
以下是可能的另一种实现方式:
```
if (dataGridView1.SelectedRows.Count > 0) // 检查是否有选中的行
{
DataGridViewRow row = dataGridView1.SelectedRows[0]; // 获取第一行
dataInfo = new 用户基本信息
{
No = yhbh.Text = row.Cells[0].Value.ToString(),
Name = yhmc.Text = row.Cells[1].Value.ToString(),
Password = yhmm.Text = row.Cells[2].Value.ToString(),
Dept = bm.Text = row.Cells[3].Value.ToString(),
Job = textBox11.Text = row.Cells[4].Value.ToString(),
Nation = zw.Text = row.Cells[5].Value.ToString(),
Birthday = dateTimePicker1.Text = row.Cells[6].Value.ToString(),
Phone = dh.Text = row.Cells[7].Value.ToString(),
Mail = yx.Text = row.Cells[8].Value.ToString()
};
}
```
该代码片段首先检查是否有选中的行,然后获取第一行,并将其数据赋值给 `dataInfo` 对象和窗体上的文本框。注意,这里使用了对象初始化器来构造 `dataInfo` 对象。
阅读全文