This is a migrated thread and some comments may be shown as answers.

HowTo: Adding new column dynamically to grid asscociated with datatable

3 Answers 261 Views
GridView
This is a migrated thread and some comments may be shown as answers.
Jorge Gonzalez
Top achievements
Rank 1
Jorge Gonzalez asked on 09 Jan 2010, 05:57 PM
Hello,
    There's probably an easier way to add a column to the grid dynamically but it gave me , a newbie, a lot of grief.

Adding a column dynamically to a grid that's associated with a datatable turned out to be relatively easy:

// Create the datatable column
newColumn = new DataColumn();
newColumn.ColumnName = <column name>;
newColumn.DataType = ..
....
<Datatable name>.Columns.Add(newColumn);
<Dataset name>.Tables[0].Columns[<column name>].SetOrdinal(<Position of the new column within the datatable>);

// Break and re-establish the link between the grid and the datatable.
<Grid name>.ItemsSource = null;
<Grid name>.ItemsSource = <Datatable name>;

// Load the new column with data by adding the data to the datatable
<datatable name>.Rows[<row index>][column index] = <data>;
<grid name>.Rebind;




3 Answers, 1 is accepted

Sort by
0
Tsvyatko
Telerik team
answered on 13 Jan 2010, 05:03 PM
Hello Jorge Gonzalez,

There are many cases where your solution can be the simplest way to avoid troubles. However it also might slow down performance. If your items source already contain the data for the new column you can use alternative solution by adding new Column directly adding it to the Columns collection and binding it to the data.

GridViewDataColumn column = new GridViewDataColumn();
column.DataMemberBinding = new Binding(".[Price]");
column.UniqueName = "Price";
column.Header = "Price";
exampleData.Columns.Add(column);


Kind regards,
Tsvyatko
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
0
Jorge Gonzalez
Top achievements
Rank 1
answered on 13 Jan 2010, 05:22 PM
Hello Tsvyatko,
   I tried this at first but the grid and the datatable were out of synch. The new column is not automatically added to the datatable.
I added the new column to both the grid and the datatable and experienced some problems, which I cannot remember at the moment what they were. That's why I used the approach I used. 
You are right about the performance. It's slower.
I will try again and document the errors I got.
Thanks
0
Jorge Gonzalez
Top achievements
Rank 1
answered on 19 Jan 2010, 04:02 PM
Hello Tsvyatko,
    I figured out what I was doing wrong. Your solution worked.

I was omitting the period and the left and right brackets in the binding command. I only put the new column name in the binding command. 

new Binding(".[Price]");
Tags
GridView
Asked by
Jorge Gonzalez
Top achievements
Rank 1
Answers by
Tsvyatko
Telerik team
Jorge Gonzalez
Top achievements
Rank 1
Share this question
or