Binding datatable to datagrid creates unnecessary rows

爷,独闯天下 提交于 2019-12-24 15:16:05

问题


I wrote code to bind a datatable to a datagrid. I tested the code with three double arrays read from three txt files. First array contains 1 2 3 with a tag of 'test1'. second array having 4 5 6 7 with test2. third one has 8 9 with test3. When I tested, data was populated on datagrid with extra rows like shown below.

test1  test2  test3
1      0      0
2      0      0
3      0      0
0      4      0
0      5      0
0      6      0
0      7      0
0      0      8
0      0      9

My intention was to show the data

test1  test2  test3
1      4      8
2      5      9
3      6      
       7   

Here is the code:

string[] filenames;

DataTable tvsa = new DataTable();

for (int i = 0; i < filenames.Length; i++)
{

    double[] a_raw = arsconv.Ama;

    // Define the columns of the table.

    DataColumn column= new DataColumn();
    column.DataType = System.Type.GetType("System.Double");
    column.ColumnName = filenames[i];
    tvsa.Columns.Add(column);

    //Define rows
    DataRow dr;
    for (int l = 0; l < a_raw.Length; l++)
    {
        dr = tvsa.NewRow();
        dr[filenames[i]] = a_raw[l];
        tvsa.Rows.Add(dr);
    }
}

datagrid_accu.ItemsSource = tvsa.DefaultView;                  

XAML:

<DataGrid Name="datagrid_accu" ItemsSource="{Binding tvsa.DefaultView}" Width="Auto" MaxWidth="500"  AutoGenerateColumns="True" >
<DataGrid.Columns>
</DataGrid.Columns>
</DataGrid>

I tested the code several times with different files and showed the same pattern. I tried to modify the code but no success. it is currently beyond my knowledge. your help will be greatly appreciated. Thanks,


回答1:


Change this part:

        //Define rows
        DataRow dr;
        for (int l = 0; l < a_raw.Length; l++)
        {
            dr = tvsa.NewRow();
            dr[filenames[i]] = a_raw[l];
            tvsa.Rows.Add(dr);
        }

To this:

        //Define rows
        DataRow dr;
        for (int l = 0; l < a_raw.Length; l++)
        {
            if ( tvsa.Rows.Count > l  )
            {
              dr = tvsa.Rows[l];
            }
            else{
              dr = tvsa.NewRow();
              tvsa.Rows.Add(dr);
            }
            dr[filenames[i]] = a_raw[l];

        }


来源:https://stackoverflow.com/questions/21171779/binding-datatable-to-datagrid-creates-unnecessary-rows

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