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

[亡魂溺海] 提交于 2019-12-04 06:11:27

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;
    }

Haven't played with datagrids a lot but you can try something like this

int currentRow = MyDataGrid.Rows.Add();

MyDataGrid.Rows[currentRow].Cells[0].Value = row1[0];  
MyDataGrid.Rows[currentRow].Cells[1].Value = row1[1];
MyDataGrid.Rows[currentRow].Cells[2].Value = row1[2];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!