rakeshvenkata
rakeshvenkata

Reputation: 137

Combox Box withing a Data Grid is not populated with data

I am doing when the form loads up

DataGridViewComboBoxColumn ComboTextCol = new DataGridViewComboBoxColumn();
            ComboTextCol.Headertext = "some";
            ComboTextCol.DataSource =  GetEmployees().Select(e => new { Name = e.LastName + " ," + e.FirstName, ID = e.EmployeeID }).ToList();
            ComboTextCol.ValueMember = "ID";
            ComboTextCol.DisplayMember = "Name";
            datagrid.Columns.Insert(0,ComboTextCol)

;

I tried this too datagrid.Columns.Add(ComboTextCol).

GetEmployees gives employee data I see the column but not the the data...??

Upvotes: 0

Views: 105

Answers (1)

Grant Thomas
Grant Thomas

Reputation: 45083

Firstly, the code you propose won't even compile - you are missing capitalisation in one area and a semi-colon at the end of the last line (and not a build issue, but I believe to display correctly you want the white space after the last name, not before). Secondly, should you amend it to do so, then there is no apparent reason for this not to display the members. Are you sure the return value of GetEmployees contains at least on element?

Consider the following:

Our employee type...

public class Employee
{
    public Employee() { }
    public Employee(int id, string firstName, string lastName)
    {
        EmployeeID = id;
        FirstName = firstName;
        LastName = lastName;
    }
    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

And within the load event of our form...

private void myForm_Load(object sender, EventArgs e)
{
    var employeeA = new Employee(28, "Charlie", "Brown");
    var employeeB = new Employee(42, "Familiar", "Stranger");
    var employees = new List<Employee>();
    employees.Add(employeeA);
    employees.Add(employeeB);

    var myDataGridView = new DataGridView();
    var myDataGridComboBoxColumn = new DataGridViewComboBoxColumn();
    myDataGridComboBoxColumn.HeaderText = "Employee";
    myDataGridComboBoxColumn.ValueMember = "ID";
    myDataGridComboBoxColumn.DisplayMember = "Name";
    myDataGridComboBoxColumn.DataSource = employees.Select(employee => new
    {
        Name = employee.LastName + ", " + employee.FirstName,
        ID = employee.EmployeeID
    }).ToList();
    myDataGridView.Columns.Insert(0, myDataGridComboBoxColumn);
    Controls.Add(myDataGridView);
    myDataGridView.Dock = DockStyle.Fill;
}

The result is absolute: the expected elements appear in the drop down box. Give it a go, and manoeuvre your way to rid your build errors to maybe, seemingly, magically proceed from this point - didn't you notice them? Note sure how you managed to 'see' anything.

Upvotes: 1

Related Questions