populate a listbox on winform with values from database
Posted on 2010-06-18 13:33 lining 阅读(205) 评论(0) 编辑 收藏 举报from->http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/9dcdf5a2-d3df-4d27-8352-1cfa9997b685
Hi,
how to populate a listbox on winform with values from database at runtime? Can someone send code / links to articles on net for this..Once user selects clicks an item from this listbox, the selected item should be shown in a textbox. I have textbox in form 1 and listbox in form 2.
Thanks to help.
=================================================================
Hi, yasinirshad,
Based on my understanding, you want to know how to get the values from a DataBase and add them into a ListBox, don't you?
I wrote a small sample for you which can do this job.
Say, I am using a Acess DB and two forms.
In form1.
Code Block
DataTable table;
BindingSource source;
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection connection = new OleDbConnection(Properties.Settings.Default.newConnectionString);
OleDbDataAdapter adapter = new OleDbDataAdapter("select NAME, ID from Table1", connection);
table = new DataTable();
adapter.Fill(table); //Retrieve data from DataBase
source = new BindingSource();
source.DataSource = table;
this.textBox1.DataBindings.Add("Text", source, "Name"); //Bind the DataSource to the TextBox
Form2 form = new Form2(source);
form.Owner = this;
form.Show(this);
}
In form2
Code Block
public Form2(BindingSource source)
{
InitializeComponent();
listBox1.DisplayMember = "NAME";
listBox1.ValueMember = "ID";
listBox1.DataSource = source;
}
And the value in your TextBox will change with the selection in your ListBox.
More info
http://msdn2.microsoft.com/en-us/library/e80y5yhx(vs.80).aspx
http://msdn2.microsoft.com/en-us/library/ef2xyb33.aspx
Hope this helps,
Regards