ADi
ADi

Reputation: 219

Datagrid add data dynamically

I am new to WPF and trying to add rows as data in DataGrid, i tried the following code, it adds rows but do not show text in rows.

I have an XElement array from which i want to loop foreach and add items in DataGrid And after successful addition is there any way to assign an ID to rows of DataGrid so when i click on row, i could get the ID for that rows specified. Please guide.

(Edit) XElement Array Containing XML

[0] => <objective id="1" title="obj 1"> </objective>
[1] => <objective id="2" title="obj 2"> </objective>
[2] => <objective id="3" title="obj 3"> </objective>

Code i tried, adds empty rows in Grid:

var datagridTopic = new DataGrid {Width = 400, IsReadOnly = true};
//I only need one column
datagridTopic.Columns.Add(new DataGridTextColumn()
{
    Header = "Topic",
    Width = datagridTopic.Width - 8 //after adding rows the grid gets scroll, so made column width lower
});

datagridTopic.Items.Add("obj 1");
datagridTopic.Items.Add("obj 2");
StackPanelContent.Children.Add(datagridTopic);

What i want to do is:

foreach (var element in XElement)
{
    string title = element.Attributes("title").ElementAt(0).Value; // obj 1
    datagridTopic.Items.Add(title);
}

Upvotes: 0

Views: 1596

Answers (1)

Nitin Joshi
Nitin Joshi

Reputation: 1666

Instead of adding data to the datagrid using code, try to bind it with the datasource you have.

var datagridTopic = new DataGrid {Width = 400, IsReadOnly = true};
//I only need one column
var column1 = new DataGridTextColumn()
{
    Header = "ID",
    Width = datagridTopic.Width - 8 //after adding rows the grid gets scroll, so made column width lower
};
column1.Binding = new Binding("ID")
datagridTopic.Columns.Add(column1);

var column2 = new DataGridTextColumn()
{
    Header = "Title",
    Width = datagridTopic.Width - 8 //after adding rows the grid gets scroll, so made column width lower
};
column2.Binding = new Binding("Title")
datagridTopic.Columns.Add(column2);

var items = xElementArray.Select(x => new { ID= x.Attribute("id").Value, Title = x.Attribute("title").Value});


datagridTopic.ItemsSource = items; //set the data source for the grid to custom created items.

StackPanelContent.Children.Add(datagridTopic);

If you don't want to display the ID in your grid, then don't add the ID column, add only Title column. you will have to implement the MouseDown event for the rows and in that row you will find the DataContext of the row which will be your data item from which you can get the ID.

Upvotes: 1

Related Questions