Gerhard Steyn
Gerhard Steyn

Reputation: 11

Fill combobox with SQL Server column values

Could you please assist me, I am trying to fill a combobox with values from a column in a SQL Server table. I have tried various methods, but none of them returned the desired result.

The error is:

Error CS1503 Argument 1: cannot convert from 'string' to 'int'

This is my code:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        fillCombo();
    }

    void fillCombo()
    {
        string con = "Data Source = xxxxx; Initial Catalog = xxxxx; Integrated Security = False; User Id = xxxxx; Password=xxxx;MultipleActiveResultSets=True";
        string Query = "select * from LEAVE ;";

        SqlConnection conDataBase = new SqlConnection(con);
        SqlCommand cmd = new SqlCommand(Query, conDataBase);

        SqlDataReader dr;

        try
        {
            conDataBase.Open();
            dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                string lveName = dr.GetString("lve_name");
                lveType.Items.Add(lveName);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }    
}

Upvotes: 0

Views: 1279

Answers (2)

waka
waka

Reputation: 3407

Always look at the signatures of the methods you are trying to use:

dr.GetString(int)

You are trying to call

dr.GetString(string)

but there's not overloaded method that accepts a string. See the documentation of GetString().

Instead, GetString requires you to pass the zero based ordinal of the column you are trying to get the string from. Let's say lve_name is the second column in your query (a bit hard to tell, since you are using SELECT * FROM, but that's another topic), you have to use it like this:

string lveName = dr.GetString(1);

Also, check what the documentation has to say:

No conversions are performed; therefore, the data retrieved must already be a string.

This means, if your query returns anything other than a string, the method will most likely throw an InvalidCastException. To prevent that from happening, you have to edit your query, like for example

SELECT lve_id, CAST(lve_name as varchar) FROM LEAVE

Another possible solution would be to access the column like this:

string lveName = dr["lve_name"].ToString()

Upvotes: 1

user8767616
user8767616

Reputation:

I would do this instead:

Dictionary<int, string> lveNames = new Dictionary<int, string>();

while (dr.Read())
{
    string lveName = dr["lve_name"].ToString();
    int lveId = int.Parse(dr["lve_id"].ToString());
    lveNames.Add(lveId, lveName);
}

lveType.DataSource = new BindingSource(lveNames, null);
lveType.DisplayMember = "lveName";
lveType.ValueMember = "lveId";
  • Assuming that you have id lve_id.
  • DisplayMember and ValueMember are used to bind the label and id to the combo box.

Upvotes: 1

Related Questions