How to add an array as row to DataGrid?

1k views Asked by At

In my program I have varying number of columns, so I've created universal input window for that which returns an array of strings

screen of input window

Now I want to add inputted data to DataGrid, but don't know how

Default DataGrid Add method supports only adding an object, so if I adding an array it just add spaces.

screen of empty row

                InputWindow iw = new InputWindow(inputs.ToArray());
                if (iw.ShowDialog() == true)
                {
                    try
                    {
                        var strings = iw.GetInputs();
                        ActiveDataGrid.Items.Add(strings);
                    }
                    catch (ArgumentException ex)
                    {
                        Debug.WriteLine($"{ex.Message} from InputWindow");
                    }
                }

Strings from InputWindow returns correctly

How can I add these values corresponding to my varying number of columns?

2

There are 2 answers

1
Diven Desu On

You might consider creating a generic class that only contains string fields. Then feed your array to the class, and then feed the class object to the data grid.

1
Will Jackson On

I assume you mean you want to add 1 value from your array to each column for each item in the array. The simplest way to do this would be to create a DataRow for each input array formatting it according to how ever many items are in the array.

    DataRow row = dataGrid.NewRow();
    foreach (var item in array)
    {
            dataGrid.Columns.Add(item);
            row[item] = item;
    }
    dataGrid.Rows.Add(row);
    dataGrid.Import.Row(row);

This would work if your plan is to process the array items one at a time and you would clear the DataGrid after each import but if that is not the case you are going to need to create some amount of generic DataColumns then enumerate through the array and columns as much as necessary to place one item in each column.