简体   繁体   English

如何将数组作为行添加到DataGrid?

[英]How to add an array as row to DataGrid?

In my program I have varying number of columns, so I've created universal input window for that which returns an array of strings 在我的程序中,我有不同数量的列,因此我为返回字符串数组的窗口创建了通用输入窗口

输入窗口画面

Now I want to add inputted data to DataGrid, but don't know how 现在,我想将输入的数据添加到DataGrid,但是不知道如何

Default DataGrid Add method supports only adding an object, so if I adding an array it just add spaces. 默认的DataGrid Add方法仅支持添加对象,因此,如果添加数组,则仅添加空格。

空行的屏幕

                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 来自InputWindow的字符串正确返回

How can I add these values corresponding to my varying number of columns? 如何添加这些值以适应不同的列数?

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. 然后将您的数组提供给类,然后将类对象提供给数据网格。

I assume you mean you want to add 1 value from your array to each column for each item in the array. 我假设您的意思是您想从数组中为数组中的每个项目的每一列添加1个值。 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,根据数组中有多少项对其进行格式化。

    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. 如果您的计划是一次处理一个数组项,并且每次导入后都将清除DataGrid,那么这将起作用,但是如果不是这种情况,则需要创建一定数量的通用DataColumns,然后通过数组枚举并尽可能多的列以在每一列中放置一项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM