Display the selected row from listview to textBox?
Asked Answered
G

3

5

How to display the selected row from listview to 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;
    }
}
Genus answered 11/7, 2013 at 17:3 Comment(3)
The code should work, what is the actual problem?Willson
There may be some exception IndexOutOfRangeException because sometimes there is no selected item in ListView.Willson
Changing the one line to ListViewItem item = listView1.SelectedItems.Count > 0 ? listView1.SelectedItems[0] : null; will cover the out of range issue.Staggard
R
7

You may want to check if there is a SelectedItem first. When the selection changed, ListView would actually unselect the old item then select the new item, hence triggering listView1_SelectedIndexChanged 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;
    }
}
Reste answered 11/7, 2013 at 17:24 Comment(0)
I
0

// select row listview check in c#

foreach (ListViewItem itemRow in taskShowListView.Items) {

            if (itemRow.Items[0].Checked == true)
            {

                int taskId = Convert.ToInt32(itemRow.SubItems[0].Text);

                string taskDate = itemRow.SubItems[1].ToString();
                string taskDescription = itemRow.SubItems[2].ToString();



            }


        }
Isoniazid answered 17/11, 2019 at 14:50 Comment(1)
Welcome to StackOverflow. Can you elaborate more your answer?Amused
P
0

Simply select the row. Iterate over the list and check which row is selected. Make operation as per the row selected. Such as,


private void delete_Items(object sender, EventArgs e)
{

    foreach(ListViewItem item in listView1.Items)
    {

      if (item.Selected == true)
      {
          // Code Here...
      }

    }

}

Physic answered 17/5, 2023 at 18:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.