将datatable绑定到datagrid会创建不必要的行 [英] Binding datatable to datagrid creates unnecessary rows
问题描述
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
我打算显示数据
test1 test2 test3
1 4 8
2 5 9
3 6
7
这是代码:
string []文件名;
DataTable tvsa = new DataTable();
for(int i = 0; i< filenames.Length; i ++)
{
double [] a_raw = arsconv.Ama;
//定义表的列。
DataColumn column = new DataColumn();
column.DataType = System.Type.GetType(System.Double);
column.ColumnName =文件名[i];
tvsa.Columns.Add(column);
//定义行
DataRow dr; (int l = 0; l {
dr = tvsa.NewRow();
dr [filenames [i]] = a_raw [l];
tvsa.Rows.Add(dr);
}
}
datagrid_accu.ItemsSource = tvsa.DefaultView;
XAML:
code>< DataGrid Name =datagrid_accuItemsSource ={Binding tvsa.DefaultView}Width =AutoMaxWidth =500AutoGenerateColumns =True>
< DataGrid.Columns>
< /DataGrid.Columns>
< / DataGrid>
我用不同的文件对代码进行了多次测试,并显示相同的模式。我试图修改代码,但没有成功。目前超出我的知识。你的帮助将不胜感激。谢谢,
更改此部分:
code> //定义行
DataRow dr; (int l = 0; l{
dr = tvsa.NewRow();
dr [filenames [i]] = a_raw [l];
tvsa.Rows.Add(dr);
}
为此:
//定义行
DataRow dr; (int l = 0; l {
if(tvsa.Rows.Count> l)
{
dr = tvsa.Rows [l];
}
else {
dr = tvsa.NewRow();
tvsa.Rows.Add(dr)
}
dr [filenames [i]] = a_raw [l];
}
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,
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];
}
这篇关于将datatable绑定到datagrid会创建不必要的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!