Skip to content
Advertisement

Convert SQL Integer into c# string for combobox (Access Database)

The following code gives me an IndexOutOfRange error. ‘Baujahr’ is an integer column in my access-database.

cbFahrzeugBJ.Items.Add(reader["Baujahr"].ToString());

Here the reader:

OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
    cbFahrzeugBJ.Items.Add(reader["Baujahr"].ToString());
}

And the whole code of this procedure:

        try
        {
            connection.Open();

            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            string query = "SELECT DISTINCT Typ FROM Autos WHERE Hersteller = @FahrzeugHersteller AND Modell = @FahrzeugModell AND Typ = @FahrzeugTyp;";
            command.CommandText = query;
            command.Parameters.Add("@FahrzeugHersteller", SqlDbType.Text);
            command.Parameters["@FahrzeugHersteller"].Value = cbFahrzeugHersteller.Text;
            command.Parameters.Add("@FahrzeugModell", SqlDbType.Text);
            command.Parameters["@FahrzeugModell"].Value = cbFahrzeugModell.Text;
            command.Parameters.Add("@FahrzeugTyp", SqlDbType.Text);
            command.Parameters["@FahrzeugTyp"].Value = cbFahrzeugTyp.Text;
            OleDbDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                cbFahrzeugBJ.Items.Add(reader.GetInt32("Baujahr").ToString());
            }

            connection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error " + ex);
        }

Advertisement

Answer

You are only including the Typ column in your result set. You will have to include Baujahr in your SELECT statement if you want to access it in your DataReader.

i.e:

 string query = "SELECT DISTINCT Typ, Baujahr FROM Autos WHERE Hersteller = @FahrzeugHersteller AND Modell = @FahrzeugModell AND Typ = @FahrzeugTyp;";
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement