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:
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
Download Sample Code : ListBox2.rar .
Now the c# code is like this:
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
Download Sample Code : ListBox2.rar .
No comments:
Post a Comment
Thanks for your comments.
-Sameer