Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding rows to a WPF datagrid where columns are not known until runtime

I'm trying to add data to a datagrid (in fact, any control that presents data in a grid will do), but the columns (both names and numbers) are not known until runtime.

The columns I DO know how to create: E.g

DataGridTextColumn textColumn = new DataGridTextColumn();
textColumn.Header = column.DisplayName;
MyDataGrid.Columns.Add(textColumn);

But how do I add rows? I don't see how I can use binding because my data is not contained in an object with known properties. For example, data for each row might come in as a string[]. So one time I might have three columns, another time I might have five.

I was expecting do be able to do something like this:

// Example data to represent a single row.
string[] row1 = new[] { "value1", "value2", "value3" };

var row = new Row;
row.AddCell(row1[0]);
row.AddCell(row1[1]);
row.AddCell(row1[2]);
MyDataGrid.Rows.Add(row);
like image 324
MrNick Avatar asked May 18 '12 10:05

MrNick


1 Answers

I'd have to start plugging away in VS to get my head round the exact code, but you can most likely just create your columns and use the column key as the binding expression seeing as indexed bindings work in WPF

I'll get some code up in a minute - but it would look something like your row creation code but with bindings on the columns that look something like (forgive the possibly incorrect method names)

textColumn.Bindings.Add(new Binding("this[" + columnIndex.ToString() + "]"));

Update:

Yeah not sure if this is what you are looking for but it works:

Created a single window with a datagrid on it (dataGrid1)

 public MainWindow()
    {
        InitializeComponent();

        var col = new DataGridTextColumn();
        col.Header = "Column1";
        col.Binding = new Binding("[0]");
        dataGrid1.Columns.Add(col);

        col = new DataGridTextColumn();
        col.Header = "Column2";
        col.Binding = new Binding("[1]");
        dataGrid1.Columns.Add(col);

        col = new DataGridTextColumn();
        col.Header = "Column3";
        col.Binding = new Binding("[2]");
        dataGrid1.Columns.Add(col);

        //dataGrid1.ad

        List<object> rows = new List<object>();
        string[] value;

        value = new string[3];

        value[0] = "hello";
        value[1] = "world";
        value[2] = "the end";
        rows.Add(value);

        dataGrid1.ItemsSource = rows;
    }

Example

like image 107
Charleh Avatar answered Nov 01 '22 15:11

Charleh