Tuesday 14 May 2013

example of listbox in c#.net

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 WindowsFormsApplication36
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //Remove from listbox;
        private void button1_Click(object sender, EventArgs e)
        {
            List<emp> lv = new List<emp>();
            lv = (List<emp>)listBox1.DataSource;
            if (listBox1.SelectedIndex >= 0)
            {
                lv.RemoveAt(listBox1.SelectedIndex);
                listBox1.DataSource = lv.ToList();
                listBox1.DisplayMember = "NAME";
                listBox1.ValueMember = "ID";
            }
        }
        public class emp
        {
            public int ID
            {
                get;
                set;
            }
            public string NAME
            {
                get;
                set;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
          
            List<emp> li = new List<emp>();
            emp o = new emp();
            o.ID=1;
            o.NAME="siv";
            li.Add(o);
            emp o1 = new emp();
            o1.ID = 2;
            o1.NAME = "sankar";
            li.Add(o1);
            listBox1.DataSource = li;
            listBox1.DisplayMember = "NAME";
            listBox1.ValueMember = "ID";
        }
        //Add in list box
        private void button2_Click(object sender, EventArgs e)
        {
            List<emp> lv1 = new List<emp>();
            emp o = new emp();
            for (int i = 0; i < listBox2.Items.Count; i++)
            {
                lv1.Add((emp)listBox2.Items[i]);
            }
            o = (emp)listBox1.SelectedItem;
            lv1.Add(o);
            listBox2.DataSource = lv1.ToList();
            listBox2.DisplayMember = "NAME";
            listBox2.ValueMember = "ID";

        }
    }
}

No comments:

Post a Comment