如何将列表视图中的选定行显示到textBox?
这是我如何做int dataGridView:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.Rows[e.RowIndex].ReadOnly = true;
if (dataGridView1.SelectedRows.Count != 0)
{
DataGridViewRow row = this.dataGridView1.SelectedRows[0];
EmpIDtextBox.Text = row.Cells["EmpID"].Value.ToString();
EmpNametextBox.Text = row.Cells["EmpName"].Value.ToString();
}
}
我试过这个:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
ListViewItem item = listView1.SelectedItems[0];
if (item != null)
{
EmpIDtextBox.Text = item.SubItems[0].Text;
EmpNametextBox.Text = item.SubItems[1].Text;
}
}
解决方法:
您可能想先检查是否存在SelectedItem.当选择更改时,ListView实际上会取消选择旧项目,然后选择新项目,从而触发listView1_SelectedIndexChanged两次.除此之外,您的代码应该工作:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
ListViewItem item = listView1.SelectedItems[0];
EmpIDtextBox.Text = item.SubItems[0].Text;
EmpNametextBox.Text = item.SubItems[1].Text;
}
else
{
EmpIDtextBox.Text = string.Empty;
EmpNametextBox.Text = string.Empty;
}
}