Copy Selected Values of a MultiSelect ListBox to TextBox in C#
In this post we will see a simple example with listbox . Here we will see how to add values to listbox at runtime . And Multi Select Property of ListBox. And how to copy selected values of listbox to textbox.
For this I am designing a form with a ListBox and 3 Textboxes as shown in image below.
Now the C# code is like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace listbox2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { listBox1.SelectionMode=SelectionMode.MultiSimple; listBox1.Items.Add("AAAAAA"); listBox1.Items.Add("BBBBBB"); listBox1.Items.Add("CCCCCC"); listBox1.Items.Add("DDDDDD"); listBox1.Items.Add("EEEEEE"); listBox1.Items.Add("FFFFFF"); listBox1.Items.Add("GGGGGG"); listBox1.Items.Add("HHHHHH"); listBox1.Items.Add("IIIIII"); listBox1.Items.Add("JJJJJJ"); } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { try { int i = listBox1.SelectedItems.Count; if (i == 1) { txtbox1.Text = listBox1.SelectedItems[0].ToString(); } if (i == 2) { txtbox2.Text = listBox1.SelectedItems[1].ToString(); } if (i == 3) { txtbox3.Text = listBox1.SelectedItems[2].ToString(); } if (i > 3) { listBox1.Enabled = false; throw new Exception(); } } catch (Exception ex) { MessageBox.Show("cannot select more than 3"); } } private void btnclear_Click(object sender, EventArgs e) { Application.Restart(); } } } |
I have written the code such that, the first selected item in a listbox will be copied to txtbox1 , second selected item will be copied to txtbox2 , third selected item will be copied to txtbox3.
See the image below