Combobox Data Binding using Datasource
In this article, I will explain about how to bind combobox using list datasource. So that we can bind both display member and value member using a datasource and also fetch selected value of the data after selected index is changed.
Combobox Data Binding using Datasource
In this article i will explain about the binding the combobox using list datasource which contains pknameslno and name. The displaymember of the comobobox is name and valuemember is pknameslno.
Following is the sourcecode to bind the combobox using List data.
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List
Program.names name1 = new Program.names();
name1.pknameslno = "1";
name1.name = "David";
namearray.Add(name1);
Program.names name2 = new Program.names();
name2.pknameslno = "2";
name2.name = "Raja";
namearray.Add(name2);
Program.names name3 = new Program.names();
name3.pknameslno = "3";
name3.name = "Singha";
namearray.Add(name3);
Program.names name4 = new Program.names();
name4.pknameslno = "4";
name4.name = "Kumar";
namearray.Add(name4);
comboname.DisplayMember = "name";
comboname.ValueMember = "pknameslno";
comboname.DataSource = namearray;
}
}
}
Code for name class used as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
public class names
{
public string _pknameslno;
public string _name;
public string pknameslno
{
get
{
return _pknameslno;
}
set
{
_pknameslno = value;
}
}
public string name
{
get
{
return _name;
}
set
{
_name = value;
}
}
}
}
}
When selectindex change event is raised it will show messagebox of the selected value of name combobox.
private void comboname_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show(comboname.SelectedValue.ToString());
}
I had attached sample code for this application.