C# dynamically create listview and add click event

Lionsure 2020-08-12 Original by the website

Use C# to develop Winforms programs. In most cases, the listview control is directly dragged to the Form, and its properties can be directly set ,its width and height can be set through the ImageList control, which can be used to meet the needs; but in some cases, the listview should not be generated in advance, and it is dynamically created when it is used. In this case, it must be dynamically added with code.

Dynamically creating a listview is nothing more than defining a listview object, which is also very simple; if you don't add a click event, it's really simple. Define an object directly and set the required attributes by referring to its properties; if you want to add a click event for it and perform related operations in the event, it is a bit more troublesome than dragging it to Form. If you have never added a click event dynamically, you may not know how to add it for a while. After adding it, how to get the dynamically created listview object in the click event.

 

Example of C# dynamically create listview and add click event

If you want to use listview to dynamically display categories, and click on a category to display all products of that category, the implementation code is as follows:

/// <summary>
       /// C# dynamically create listview
       /// </summary>

       private void AddCategories()
       {
              ListView lvCategory = new ListView();
              lvCategory.View = View.LargeIcon;
              lvCategory.BorderStyle = BorderStyle.None;
              lvCategory.Cursor = Cursors.Hand;//Set the mouse to hand

       lvCategory.Left = 430;
              lvCategory.Width = 500;
              lvCategory.BackColor = Color.lFromArgb(216, 222, 230);//Background color

       //Add a click event
              lvCategory.SelectedIndexChanged += new EventHandler(lvCategory_SelectedIndexChanged);

       lvCategory.Items.Add("Computer");
              lvCategory.Items.Add("Notebook");
              lvCategory.Items.Add("Mobile");
              lvCategory.Items.Add("Digital Camera");
              lvCategory.Items.Add("LCD TV");
              lvCategory.Items.Add("Washing machine");
              this.Controls.Add(lvCategory);
       }

// listview click event
       private void lvCategory_SelectedIndexChanged(object sender, EventArgs e)
       {
              ListView lvCategory = (ListView)sender;//Get dynamically created listview object
              if (lvCategory.SelectedItems.Count > 0)
              {
                     string categoryName = lvCategory.SelectedItems[0].SubItems[0].Text;//Binding products
              }
       }

Defining the listview object is very simple. The key is how to get the newly created object in the click event, which can be achieved by using (ListView)sender in the code.