HelloIT
HelloIT

Reputation: 172

C#: Connection fails to fill control elements from DataTable

I'm establishing a SqlServer database connection in order to retrieve data from a table and feed them as input in textboxes and comboboxes.

Despite the fact that I don't get any exception or error message the result is not the expected, even though all the data is returned an stored into the table, two comboboxes don't behave as expected. Furthermore two mention the gear behind the controls is placed in a picturebox which all together "seats" on a panel!

This is my code:

            try
            {
                using (SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=SmartCity;Integrated Security=True"))
                {

                    DataTable db = new DataTable();
                    SqlDataAdapter sda = new SqlDataAdapter("SELECT card_type,card_n
                    umber,exp_month,exp_year,cvv FROM CreditCards WHERE user_id='" + ApplicationState.CurrentUser.userid.ToString() + "'", con);
                        sda.Fill(db);

                    //MessageBox Prints the missing data perfectly though!
                    MessageBox.Show("Cart Type:" + db.Rows[0][0].ToString() 
                    + "\nExpiration Month:" + db.Rows[0][2].ToString()); 

                    txtcardholername.Text = ApplicationState.CurrentUser.name + " " + ApplicationState.CurrentUser.surname;
                    cboxcardtype.Text = db.Rows[0][0].ToString();
                    txtcardnumber.Text = db.Rows[0][1].ToString();
                    cboxmonth.Text = db.Rows[0][2].ToString();
                    cboxexpyear.Text = db.Rows[0][3].ToString();
                    txtcvv.Text = db.Rows[0][4].ToString();
                }

            }
            catch (Exception)
            {
                MessageBox.Show("Something went wrong!");
            }

Upvotes: 0

Views: 64

Answers (2)

numaroth
numaroth

Reputation: 1313

Solution by the original asker:

This small detail was the problem:

When I created the month combo box I added the following values:

First Initialization

Hence the database returned -6- as month NOT -06- which weren't included in the items of the combobox at the beggining.

Then I changed the values as shown in the picture bellow.

After Changing the values

Voilà:

enter image description here

Upvotes: 1

NicoRiff
NicoRiff

Reputation: 4883

You don´t fill a combobox by setting it´s Text property. To properly fill the ComboBox you have to add items to it:

comboBox1.Items.Add(db.Rows[0][0].ToString());

Then you have to select it and you´ll be OK.

comboBox1.SelectedItem = comboBox1.Items.Cast<KeyValuePair<string,string>>().First(item=> item.Value == db.Rows[0][0].ToString());

Upvotes: 0

Related Questions