Search code examples
c#wpfdatatabledatagrid

How to add DataGridViewComboboxColumn to a Datagrid


I am creating a table view where some info is given and the user gets a chance to add some additional info found in a Combobox.

Adding the normal text fields is no problem. But when I try to add the Combobox column I get the following error:

Error CS1503 Argument 1: cannot convert from >'System.Windows.Forms.DataGridViewComboBoxColumn' to >'System.Data.DataColumn' test C:\Users\TomekJasinski\Documents>\Hello_world\test\test\Window1.xaml.cs 52 Active

private void populateGrid(List<String> str) 
{

     DataTable table = new DataTable();

     DataColumn xCord = new DataColumn("X Cord", typeof(string));
     DataColumn yCord = new DataColumn("Y Cord", typeof(string));
     DataColumn rotation = new DataColumn("Rotation", typeof(string));
     DataColumn partRef = new DataColumn("Part Reference", typeof(string));
     DataColumn partNumb = new DataColumn("Part Number", typeof(string));

     table.Columns.Add(xCord);
     table.Columns.Add(yCord);
     table.Columns.Add(rotation);
     table.Columns.Add(partRef);
     table.Columns.Add(partNumb);

     DataGridViewComboBoxColumn dgvCmb = new DataGridViewComboBoxColumn();
     dgvCmb.HeaderText = "Name";
     dgvCmb.Items.Add("Ghanashyam");
     dgvCmb.Items.Add("Jignesh");
     dgvCmb.Items.Add("Ishver");
     dgvCmb.Items.Add("Anand");
     dgvCmb.Name = "cbColumn";
     table.Columns.Add(dgvCmb); // <- Error

     foreach (string current in str)
     {
           string[] temp = current.Split(Convert.ToChar(","));
           DataRow row = table.NewRow();
           row[0] = temp[0];
           row[1] = temp[1];
           row[2] = temp[2];
           row[3] = temp[3];
           row[4] = temp[4];

           table.Rows.Add(row);
      }
      dataGrid.ItemsSource = table.DefaultView;
}

Solution

  • You should add a System.Windows.Controls.DataGricComboBoxColumn to the DataGrid:

    DataGridComboBoxColumn dgvCmb = new DataGridComboBoxColumn();
    dgvCmb.ItemsSource = new List<string>
    {
        "Ghanashyam",
        "Jignesh",
        "Ishver",
        "Anand"
    };
    dataGrid.Columns.Add(dgvCmb);
    

    WPF isn't Windows Forms. In WPF, you generally define UI elements in XAML.