1

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 Answer 1

2

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

        }
Sign up to request clarification or add additional context in comments.

3 Comments

i had to modify the logic to >=
Hi Thanks for your kind answer, I tried to use your code and encountered build error which message is "Cannot apply indexing with[] to an expression of type 'System.Data.DataTable' pointing ' dr = tvsa[l]; '. Any comments? Again, thanks,
there is a checkmark next to my answer, if you click it i get points... =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.