0

I am not sure where I did wrong in these lines. The codes are supposed to fetch data from database and assign it into the combo box. But there is no data displayed in the combo box list. My codes:

public void employeeListCombo()
{

    Employee employeeList = new Employee();

    Dataset employees = employeeList.getAllEmployee();

    foreach(DataRow dr in employees.Tables[0].Rows){

     String   selectedEmp = dr["firstName"].ToString();

        comboEmployee.DataSource = selectedEmp;

    }
    }
  • I had a question that might be of interest to you. See [Dataset from database is empty](http://stackoverflow.com/questions/29448761/dataset-from-database-is-empty). – mmking Apr 06 '15 at 02:16
  • @mmking, my sql connection is establish in a different file and that allows me not to use these lines SqlDataAdapter adapter = new SqlDataAdapter(); SqlCommand command = new SqlCommand("SELECT * FROM Orders"); string connString = @"Data Source=localhost\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True"; SqlConnection conn = new SqlConnection(connString); Could you point where did i do wrong? – Chloe Benjiman Apr 06 '15 at 02:44
  • If comboEmployee is your combobox, you are setting your DataSource to a different string for each data row. – mmking Apr 06 '15 at 03:22
  • @mmking, I see where you are going with this. Is there any way that I can use beside the example you gave me just now? – Chloe Benjiman Apr 06 '15 at 05:15
  • Well, you might take a look at [C# - Fill a combo box with a DataTable](http://stackoverflow.com/questions/256832/c-sharp-fill-a-combo-box-with-a-datatable), but I see that @DonBoitnott has already given you a pretty good answer. – mmking Apr 06 '15 at 13:53
  • Will definitely check it out. Thanks @mmking! – Chloe Benjiman Apr 07 '15 at 00:38

1 Answers1

0

Since you seem to want to use DataBinding on the ComboBox, you should do this:

public void employeeListCombo()
{
    var employeeList = new Employee();
    var employees = employeeList.getAllEmployee();
    comboEmployee.DataSource = employees.Tables[0].DefaultView;
    comboEmployee.DisplayMember = "firstName";
}

However, your original code could also be made to work:

public void employeeListCombo()
{
    var employeeList = new Employee();
    var employees = employeeList.getAllEmployee();
    if (employees.Tables.Count > 0)
    {
        foreach(DataRow dr in employees.Tables[0].Rows)
        {
            var selectedEmp = dr["firstName"] as String;
            if (!String.IsNullOrEmpty(selectedEmp))
                comboEmployee.Items.Add(selectedEmp);
        }
    }
}

The choice depends on what you mean to do with the items in the ComboBox later. If you need to get at the selected data as more than just the string that is selected, you would likely benefit from binding. Otherwise, the second approach is fine.

DonBoitnott
  • 10,787
  • 6
  • 49
  • 68