Schreiberito
Schreiberito

Reputation: 29

Selecting value from MySQL table based on combobox selection?

I have a combobox with values populated from one table. When I select a value from this combobox, I'd like to display the corresponding value from another table.

I've tried typing the SQL command a few different ways, but it keeps giving me errors.

When I try:

            MySqlCommand serialBox_1 = new MySqlCommand("Select serial_Units from Units where " + stationSelection_1 = "station_Units", connection);

it tells me the left-side of an assigner must be a variable, property, or indexer. When I try 2 equal signs, it tells me it cannot convert a bool to a string.

Here's the whole block of code:

 public MainWindow()
        {
            InitializeComponent();


            string connectionString = "SERVER=localhost;DATABASE=dbname; UID=myPC;Password=mypw;"; 

            MySqlConnection connection = new MySqlConnection(connectionString); 

            MySqlCommand stationList = new MySqlCommand("Select stationNumber_stations from stations", connection); 
            connection.Open(); 


            DataTable dt_stations = new DataTable(); 
            dt_stations.Load(stationList.ExecuteReader()); 
            connection.Close(); 

            stationComboBox_1.DataContext = dt_stations;
            stationComboBox_1.ItemsSource = dt_stations.DefaultView;

            string stationSelection_1 = stationComboBox_1.Text;


            MySqlCommand serialBox_1 = new MySqlCommand("Select serial_Units from Units where " + stationSelection_1 = "station_Units", connection);

The first command for the dropdown works just fine, but the command to select the serial does not.

Example of what I'd like to do:

Tables: Stations & Units

Stations columns: Station #, IP address, MAC

Units column: Station #, status, serial #

Combobox selection: Station # 5

Text to display: The serial # of the unit in station #5.

I want to be able to click a "station number" in the dropdown & have the "serial #" display in a textbox.

Upvotes: 2

Views: 733

Answers (1)

Nicola Uetz
Nicola Uetz

Reputation: 858

Your sql query is slightly wrong. You should use ' at the beginning and at the end of a String in an SQL-Query since MySQL does not know when it is a String and when another field of your MySQL-Table that just has the same name. The second thing you did wrong is not puttin the = into your query but like a + into after stationSelection_1

MySqlCommand serialBox_1 = new MySqlCommand("Select serial_Units from Units where " + stationSelection_1 = "station_Units", connection);

should be

MySqlCommand serialBox_1 = new MySqlCommand("Select serial_Units from Units where station_Units='" + stationSelection_1 + "'", connection);

Upvotes: 1

Related Questions