Nant
Nant

Reputation: 569

Show items in listbox from database in C#

I have have a database with two tables Countries and Websites. I am displaying all countrynames in listbox1 with the following statement:

try
{

    connection.Open();
    using (OleDbCommand command = new OleDbCommand())
    {
        command.Connection = connection;
        command.CommandText = "SELECT CountryName FROM Countries ";
        //whenever you want to get some data from the database
        using (OleDbDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                listBox1.Items.Add(reader["CountryName"].ToString());
            }
        }
    }
}
catch (Exception l)
{
    MessageBox.Show("Error:" + l);
}
finally
{
    connection.Close();
}

However know based on what Item the user selects in listbox1 I want listbox two to display the relevant websites that are linked to the country in the database. The foreign key in the website table is CountryIDFK and I want to display the field WebsiteName of the second table.

I somehow don't know how to show the items in listbox2. I don't want to add them in the second listbox but rather just show based on what country the user has selected. Can someone assist please ?

Upvotes: 1

Views: 20503

Answers (2)

sali
sali

Reputation: 9

For Exam:

tbl_tableFilds: ID,Title

in EF:

var Result=tbl_Table.where().tolist();
ListBox1.Datasource=Result;
ListBox1.DisplyMemmber="Title";
ListBox1.ValueMember="ID";

another way is :

in EF:

var Result=tbl_Table.where().tolist();
foreach(var item in Result) {
  ListBox1.items.Add(item.Title);
  }

Upvotes: 0

MaticDiba
MaticDiba

Reputation: 905

First of all, you could bind your datasource. This means that you could bind DataTable or object list to your listbox. Example is avaliable here: https://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.datasource%28v=vs.110%29.aspx This way you will be able to store your Id and country name in you listbox items list.

Afterwards you could use SelectedValueChanged event handler which is also demonstrated in the example above. In the handler method you just populate your second listbox.

Upvotes: 1

Related Questions