Display selected row from list in textBox?

How to display a selected row from a list in a textBox?

This is how I do 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(); } } 

I tried this:

 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; } } 
+4
source share
1 answer

You can check if there is a SelectedItem first. When the selection has changed, the ListView actually deselects the old item, and then selects the new item, so listView1_SelectedIndexChanged run twice. Other than that, your code should work:

 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; } } 
+5
source

Source: https://habr.com/ru/post/1490961/


All Articles