0

How can I link two different tables from a database to combobox ?

My combobox connection to the table is done with this code :

 combobox1.ItemsSource = database.Mavads.ToList();
            combobox1.DisplayMemberPath = "MavadName";
            combobox1.SelectedValuePath = "MavadFe";

And:

<ComboBox HorizontalAlignment="Left" Margin="826,168,0,0" VerticalAlignment="Top" Width="120" Name="combobox1" SelectionChanged="combobox1_SelectionChanged" TabIndex="3"  IsTextSearchEnabled="True" Loaded="combobox1_Loaded"   />

This code is work correctly but just shows one table. I need both tables, not just one! What should I do?

emy shoj
  • 25
  • 4
  • `database.Mavads.ToList()` is the first table? How do you get the data from second table? All data you want to show in `ComboBox` goes into `ItemsSource`. – FredM Feb 08 '19 at 09:01
  • @FredM yes it first table ,Actually this is my question, how to connect second table? – emy shoj Feb 08 '19 at 09:06
  • 1
    You should do a SQL Query, joining your 2 tables, then set your DataSet made by sql query to your ItemSource. – koviroli Feb 08 '19 at 09:11
  • @koviroli is right. You could do a [`.AddRange()`](https://stackoverflow.com/questions/1528171/joining-two-lists-together) to join two lists together, but doing it on SQL side feels better. – FredM Feb 08 '19 at 09:12
  • The sql statement you would use is union. Inner join would be a bit pointless since you only get entries match from both tables. If mavadfe is just an id then when you pick one, how do you know which table it came from? – Andy Feb 08 '19 at 10:11
  • @Andy how to use it? – emy shoj Feb 08 '19 at 15:02
  • https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ado-net-code-examples – Andy Feb 08 '19 at 15:06

1 Answers1

0

So like I metioned in comment below your question:

1) Write a SQL Query

2) Connect your DB

3) Do the Query

4) Read your results

5) Bind it to your combobox

You cannot add multiple datasource to your combobox, so you should do one table from 2 tables in code.

Something like this in code, but you should do modifications(eg. connectiong string, database, table name..).

string sqlQuery = "SELECT * FROM Mavads INNER JOIN OtherTable ON Mavads.CD = OtherTable.AB;"
using (SqlConnection sqlConnection = new SqlConnection("YourConnectionString"))
{
    SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConnection);
    sqlConnection.Open();
    SqlDataReader sqlReader = sqlCmd.ExecuteReader();

    while (sqlReader.Read())
    {
        comboBox.Items.Add(sqlReader["name"].ToString());
    }

    sqlReader.Close();
}
koviroli
  • 1,422
  • 1
  • 15
  • 27
  • I want show "MavadName" from table "Mavad" and "Mahname"from table "Mah" and for ValuePath show me "MavadFe" and "MahFe" but your code dont have value – emy shoj Feb 08 '19 at 11:54