C# ListView – Set Selected Rows To TextBoxes

In this example,we see how to set the selected items in a multi-column listview to their respective textboxes.This is the deal :

  • First we fill the ListView with data.
  • We are using a multicolumn listview.
  • When the user selects a given row,we set the selected row cells to their respective textboxes.

Here's the code :

using System;
using System.Windows.Forms;

namespace csharp_ListView_With_ImagesNText
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
      //SET LV PROPIETIES
      listView1.View = View.Details;
      listView1.FullRowSelect = true;

      //ADD COLUMNS
      listView1.Columns.Add("Name", 150);
      listView1.Columns.Add("Position", 150);
      listView1.Columns.Add("Team", 150);
    }

    //ADD ROW
    private void add(string name,String pos,String team)
    {
      //ARRAY TO REP A ROW
      String[] row = { name, pos, team };

      ListViewItem item = new ListViewItem(row);

      //ADD ITEMS
      listView1.Items.Add(item);
    }

    private void addBtn_Click(object sender, EventArgs e)
    {
      add(nameTxt.Text, posTxt.Text, teamtxt.Text);

      //CLEAR TXT
      nameTxt.Text="";
      posTxt.Text="";
      teamtxt.Text = "";
    }
    //CLEAR
    private void clearBtn_Click(object sender, EventArgs e)
    {
      listView1.Items.Clear();

      //CLEAR TXT
      nameTxt.Text = "";
      posTxt.Text = "";
      teamtxt.Text = "";

    }
    //GET SELECTED ITEMS

    private void listView1_MouseClick_1(object sender, MouseEventArgs e)
    {
      String name = listView1.SelectedItems[0].SubItems[0].Text;
      String pos = listView1.SelectedItems[0].SubItems[1].Text;
      String team = listView1.SelectedItems[0].SubItems[2].Text;

      nameTxt.Text = name;
      posTxt.Text = pos;
      teamtxt.Text = team;
    }

  }
}

Best Regards.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *