0

i want to add new columns and rows to a C# WPF ListView (GridView) at runtime. As far as i know you can only add rows to a gridview by using anonymous objects or classes with a static set of members to which the columns are bound. Is there a way to do this at runtime that the user is able to add a new column, bind this column to something and add new data?

thx ooorndtski

1
  • Please be more specific, show some example code. Commented Jun 5, 2013 at 8:45

2 Answers 2

1

Yes, you can do this in code an runtime. You need the GridView as a variable (give it a name in XAML to auto-generate that variable in Visual Studio). The GridView has a Columns property that you can handle like any other collection, you can add and remove for example.

This is the example from MSDN (The gridview name "myGridView"):

GridViewColumn gvc3 = new GridViewColumn();
gvc3.DisplayMemberBinding = new Binding("EmployeeNumber");
gvc3.Header = "Employee No.";
gvc3.Width = 100;
myGridView.Columns.Add(gvc3);

Generally speaking, anything you can do in XAML, you can do in code.

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

2 Comments

Thank you for the answer. Let's assume that there are already 2 columns when the program starts. To put some data into the listview i can use an ObservableCollection<object> oc = new ObservableCollection<object>(); and add anonymous objects: oc.Add(new { col1 = "A", col2 = "B" });. If i add a new column i want to add data into that new column too. How can i achieve this? Anonymous objects are static and can not be changed at runtime.
They can be if you name them to their according object ID. You loop through the controls and parse their name for the ID. The button that was created dynamically with the name btn_21 will grab 21 and parse through other controls names, if 21, then do something with is. if(c is TextBox)...
0

So, what i was looking for is described in this thread. He creates a new Dictionary-class, which implements the INotifyPropertyChanged interface. When adding data to the dictionary an event is triggered.

At the place in your code where you want to add a new row, you just put the data into an object of this Dictionary class and add the Dictionary to an ObservableCollection which is bound to the DataGrid.

Comments

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.