Click here to Skip to main content
15,917,455 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
In my tblSates Table, I have a column named Monat with these three values [01.2016, 02.2016 and 03.2016] and I want to fetch these values in a combobox.

I am getting the values but just two of them instead of all three. And I debug I stil get two values.
[02.2016 and 03.2016]
Here my code:

C#
private void FillCombobox2()
    {
        string S = ConfigurationManager

        // TSQL-Statement
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = ("SELECT DISTINCT Monat from tblSales");            
        SqlDataReader myReader;
        try
        {
            con.Open();
            myReader = cmd.ExecuteReader();
            if (myReader.Read())
            {
                DataTable dt = new DataTable();
                dt.Load(myReader);
                combobox1.DisplayMember = "Monat";
                combobox1.ValueMember = "Monat";
                combobox1.DataSource = dt;
                combobox1.SelectedIndex = -1;

            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            con.Close();
        }
    }
Posted
Updated 21-May-15 1:52am
v2
Comments
Sinisa Hajnal 21-May-15 6:41am    
Your Periode1.SelectedValue is most probably null / nothing / not set.
Either check for it and put dbnull.value into the parameter or give it some default value and check in SP for it
kashif Atiq 21-May-15 8:08am    
what is the data type of column Monat?

1 solution

C#
private void FillCombobox2()
    {
        string S = ConfigurationManager
 
        // TSQL-Statement
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = ("SELECT DISTINCT Monat from tblSales");            
        //SqlDataReader myReader;
        try
        {
            con.Open();
         SqlDataAdapter ad = new SqlDataAdapter(cmd);
         DataTable dt = new DataTable();
                ad.Fill(dt)             
                combobox1.DisplayMember = "Monat";
                combobox1.ValueMember = "Monat";
                combobox1.DataSource = dt;
                combobox1.SelectedIndex = -1;
 
            }
 
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            con.Close();
        }
    }
 
Share this answer
 
Comments
Sinisa Hajnal 21-May-15 8:15am    
Aha, I get it, you removed reader.Read call which advanced your position (and skipped one of your three records)

In your original code, replace reader.Read with reader.HasRows and you'll be all set.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900