Datagrid add data dynamically - c#

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);
}

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.

Related

Devexpress - how to add columns to multilevel gridView

I'm trying to make two-level grid control. It has some package with its elements. I want to add one more column to gridView3 and hide three columns. I'm sending data to this gridView in code (dataset - 2 tables with one relation).
I've tried to send data to this gridcontrol and then operate on gridviews
gridControl2.DataSource = value.Tables[0];
gridView3.PopulateColumns(value.Tables[1]);
gridView3.Columns["RpkeId"].Visible = false;
gridView3.Columns["SourceLueId"].Visible = false;
gridView3.Columns["NewLueId"].Visible = false;
and then I'm trying to add column:
var test = new List<int> { 1, 12, 123, 1234 };
RepositoryItemComboBox riComboBox = new RepositoryItemComboBox();
riComboBox.Items.AddRange(test);
gridControl2.RepositoryItems.Add(riComboBox);
GridColumn columnGIDNumer = new GridColumn();
columnGIDNumer.FieldName = "asdfasdfa";
columnGIDNumer.ColumnEdit = riComboBox;
columnGIDNumer.OptionsColumn.AllowEdit = true;
gridView3.Columns.Add(columnGIDNumer);
None of these seem to work:
Is there any event I need to invoke or something? It seems that it'd work in normal, one-level gridcontrol.
Thanks in advance!

Dynamically add data to columns in GridView

I have the following code that dynamically creates columns within a WPF GridView control, the header names come from a string[] which is stored in a List<string[]> named data_org
GridView gv = tabell.View as GridView;
foreach (string s in data_org.ElementAt(0))
{
gv.Columns.Add(new GridViewColumn { Header = s });
}
Is there a way to add data while I'm creating the columns? I've searched for ways of doing it in the add column statement but can't find a way.
gv.Columns.Add(new GridViewColumn{Header = s, **statement to add data to column**});
My data is stored in another List<float[]>, where each item float[] represents a column. Do I have to do something to handle that data type (float[]), too?
You do not add data items directly to the columns of a GridView. Instead, you set the ItemsSource of the associated ListView, which is tabell in your case.
tabell.ItemsSource = /* Set a binding or assign an items collection. */;
Then you would create bindings for each column to the corresponding properties on your data items that should be displayed in the columns using DisplayMemberBinding.
var gridViewColumn = new GridViewColumn
{
Header = s,
DisplayMemberBinding = new Binding(/* Binding property path / name of the property. */);
};
As you only have a list of floats for each column, you should create a suitable data item type first. The ItemsSource expects a list of items that contain properties for each column, it represents a row.
What you have to do now is:
Create a row data type that contains properties for each column
public class MyDataItem
{
public float Number { get; }
// ...properties for other columns..
}
Create a collection of these data items with data from you float lists.
var myDataItemList = new List<MyDataItem>();
// ...create data items, add your data and add the items to the list.
Assign the list as items source of the ListView.
tabell.ItemsSource = myDataItemList;
Add display member bindings for each column.
var gridViewColumn = new GridViewColumn
{
Header = s,
DisplayMemberBinding = new Binding(nameof(MyDataItem.Number));
};
Then it should work. However, I recommend you to have a look at the MVVM design pattern.

WPF specify row in grid of programmatically created datagrid

I'm trying to find out how can I set up row and columnspan of programmatically created DataGrid. My code adds it in the first row:
private DataGrid CreateTextBoxesDataGrid(string name)
{
DataGrid dataGrid = new DataGrid();
dataGrid.Name = name;
//row ???
dataGrid.Style = Resources["AppSettingsDataGridStyle"] as Style;
dataGrid.Columns.Add(CreateNameColumn());
dataGrid.Columns.Add(CreateTextValueColumn());
dataGrid.Columns.Add(CreateComentColumn());
return dataGrid;
}
...
mainGrid.Children.Add(CreateTextBoxesDataGrid("eeej"));
To set a ColumnSpan on the DataGrid itself does not really make sense. The ColumnSpan defines how many columns a control on the grid will span across. So as you see, this is something you want to set per control that is INSIDE the grid, not on the grid itself.
Are you intending to set the width of the column of the DataGrid? If that is the case, you can do something like this:
column.Width = new DataGridLength(1, DataGridLengthUnitType.Auto);
Or like this if you want it based on the entire width of the DataGrid:
column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
If you want to add a new row programatically to the DataGrid, you can do this:
public class DataGridRow
{
public string Col1 { get; set; }
public string Col2 { get; set; }
}
...
var row = new DataGridRow{ Col1 = "Column1", Col2 = "Column2" };
dataGrid.Items.Add(row);
If you want to set how many columns the DataGrid will span inside it's parent grid, you can use the following:
Grid.SetColumnSpan(dataGrid, columnsToSpan);
I'm just guessing what you want here, if I did not understand you correctly, feel free to reply to my answer with more details.
That's the code:
Grid.SetColumnSpan(dataGrid, colSpan);
Grid.SetRow(dataGrid, row);

How can I bind the rowheight between two DataGrids?

I have two DataGrids with the same number of rows. But it can be that a row in DataGrid1 has more text in it and the rowheight will be bigger than in DataGrid2. I already tried something like this:
for (int i = 0; i < DataGrid1.Items.Count; i++)
{
DataGrid1.ScrollIntoView(DataGrid1.Items[i]);
DataGridRow row = (DataGridRow)DataGrid1.ItemContainerGenerator.ContainerFromIndex(i);
Binding bindingHeight = new Binding();
bindingHeight.Mode = BindingMode.TwoWay;
bindingHeight.Source = row.ActualHeight;
bindingHeight.Path = new PropertyPath(DataGridRow.HeightProperty);
DataGrid2.ScrollIntoView(DataGrid2.Items[i]);
DataGridRow row2 = (DataGridRow)DataGrid2.ItemContainerGenerator.ContainerFromIndex(i);
BindingOperations.SetBinding(row2, DataGridRow.HeightProperty, bindingHeight);
}
Any ideas how I can get the rows to have the same height?
Edit:
The problem is that i want to bind the rowheight of a single row.
This is how it looks at the moment:
But I want that a specific row in DataGrid2 has the rowheight of the other row in DataGrid1. So e.g. that the row with the ID 12940 + rm in DataGrid2 has the same height as the row in DataGrid1.
You should define the binding in XAML: RowHeight="{Binding ElementName=m_DataGrid1, Path=RowHeight}"
Or if you really want to bind in code behind:
m_DataGrid2.SetBinding(DataGrid.RowHeightProperty, new Binding("RowHeight")
{
Source = m_DataGrid1
});

How to populate DataGridView with textbox and combobox with comboboxcells having different value lists

I have three columns , textbox, combobox and textbox in that order:
this.columnLocalName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.columnLocalAddress = new System.Windows.Forms.DataGridViewComboBoxColumn();
this.columnLocalPort = new System.Windows.Forms.DataGridViewTextBoxColumn();
And they are in turn in a datagridview like so:
this.dataGridViewLocalProfile.Columns.AddRange(
new System.Windows.Forms.DataGridViewColumn[] {
this.columnLocalName,
this.columnLocalAddress,
this.columnLocalPort});
Later on I will try to add different values to each combobox cell like so:
foreach (profile in localProfile.List)
{
DataGridViewComboBoxCell cell =(DataGridViewComboBoxCell)
(dataGridViewLocalProfile.Rows[dataGridViewLocalProfile.Rows.Count - 1].
Cells["columnLocalAddress"]);
cell.Items.Clear();
cell.Items.Add(profile.Address.ToString());
dataGridViewLocalProfile.Rows.Add(
new string[] { profile.Name, profile.Address, profile.Port });
}
This results in a datagrid with the first column and last column populated and the comboboxcolumn empty. with an dataerror which I handle. The message is:
DataGridViewComboBoxCell value is not valid.
I have read through most of the post, but can not find a solution to this.
I have tried with setting the datasource like so:
cell.DataSource = new string[] { profile.Address };
still getting empty comboboxcolumn with an dataerror saying
DataGridViewComboBoxCell value is not valid.
I think this is extra tricky since I add different values for each comboboxcell.
Can anyone, please help me as to how i can make this work.
/Best
Late to the game, but here's the solution anyways.
The problem is in the foreach loop. The ComboBox cell from the last existing row is populated with an item. But then, a whole new row is added using the current profile object:
dataGridViewLocalProfile.Rows.Add( new string[] { profile.Name, profile.Address, profile.Port });
The items for the ComboBox cell in this new row is empty, therefore profile.Address is not valid. Change the foreach loop to look like this and you're gold:
foreach (Profile p in this.localProfile)
{
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(this.dataGridView1);
DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)row.Cells[1];
cell.Items.Clear();
cell.Items.Add(p.Address);
row.Cells[0].Value = p.Name;
row.Cells[1].Value = p.Address;
row.Cells[2].Value = p.Port;
this.dataGridView1.Rows.Add(row);
}

Categories

Resources