Get DataGrid row by index - c#

I am trying to obtain DataGridRow from my DataGrid based on index. I am using following code:
public DataGridRow GetGridRow(int index)
{
DataGridRow row = (DataGridRow)DG_Statement.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
// May be virtualized, bring into view and try again.
DG_Statement.UpdateLayout();
DG_Statement.ScrollIntoView(DG_Statement.Items[index]);
row = (DataGridRow)DG_Statement.ItemContainerGenerator.ContainerFromIndex(index);
}
return row;
}
Ref Link - Get row in datagrid
But unfortunately its returning a null object of DataGridRow.
If I check the Items[] property of my grid I could see 13 items.
Need suggestion on how to obtain the Grid Row as I want to change color of top 2 and bottom 2 rows of my data grid.
Any help is appreciated. Thanks!!
Adding Screenshot of DataGrid Items
Important Update
If I call GetGridRow() from the SelectedIndexChanged Event of the Grid it works flawlessly.
On the other hand, if I call it after I construct the object of the page on which my grid is displayed it returns row object as NULL.

So if its in the code behind. You can just get the selected index of the DataGrid. I've named the datagrid dataGrid as an example.
var rowIndex = dataGrid.SelectedIndex;
var row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(selectedIndex);

Check to make sure the index you're passing in is actually within bounds.

Related

DisplayIndex reading incorrectly when rows hidden

The goal is to copy the selected cell data out of a selected row.
I'm doing this by catching the CopyingRowClipBoardContent event inside my datagrid and redirecting it to this code:
var currentCell = e.ClipboardRowContent[VwrGrid.CurrentCell.Column.DisplayIndex];
e.ClipboardRowContent.Clear();
e.ClipboardRowContent.Add(currentCell);
This works perfectly! the only issue, is that if some of the columns are hidden, DisplayIndex reads improperly.
So if we have Item 1, Item 2, and Item 3.
If all are showing and I selected item3 and copy it, I get the cell value in Item 3.
The problem is, If Item 2 is collapsed/not shown, then copying Item 3 will tell you you're trying to copy out of bounds. because it's counted displayIndex , 3 from the left, and only two were shown. so it's moved outside of the table
For WPF Datagrid, try this:
// The clipboard row works only for visible cells
// To obtain the data column use the columnIndex and then map that to the Columns collection
int columnIndex = dataGrid.CurrentCell.Column.DisplayIndex;
var column = dataGrid.Columns[columnIndex];
// Now get the needed column
var cellContent = e.ClipboardRowContent.Where(i => i.Column == column).First();
e.ClipboardRowContent.Clear();
e.ClipboardRowContent.Add(cellContent);
For Winforms:
Use .Index instead. .DisplayIndex applies only to visible columns.
Because this is WPF and I can't simply use an index, I just iterated through the columns and counter the number of columns that had their visibility set to collapsed up to the column we were attempting to grab the displayindex for. Then subtracted that number from the displayIndex.
private void DataGrid_CopyingRowClipboardContent(object sender, DataGridRowClipboardEventArgs e)
{
//because we need to use displayindex, we need to check how many collapsed columns there are before our column, and adjust our display index accordingly
int invisibleCols = 0;
foreach(DataGridColumn col in VwrGrid.Columns)
{
if (col.Visibility == Visibility.Collapsed)
invisibleCols++;
if (col.Header.ToString() == VwrGrid.CurrentCell.Column.Header.ToString()) break;
}
try
{
var currentCell = e.ClipboardRowContent[VwrGrid.CurrentCell.Column.DisplayIndex - invisibleCols];
e.ClipboardRowContent.Clear();
e.ClipboardRowContent.Add(currentCell);
}
catch
{
}
}

Searching DataGrid for matching values

I Have a data grid which can be queried based on a comboBox choice .
My code (shown below) is meant to search through the datagrid and if it finds a row with a matching piece of text it is meant to move the datagrids selected index to the corresponding row.
for (int i = 0; i <= DashBoard_DataGrid.Columns.Count - 1; i++)
{
if (DashBoard_DataGrid.Rows[0].ToString().ToLower().Contains(comboBox9.Text.ToString().ToLower()))
{
value = dr.Cells[i].Value.ToString();
// return dr.Cells[i].RowIndex;
DashBoard_DataGrid.SelectedCells[i].RowIndex = dr.Cells[i].RowIndex;
}
}
However I am getting the following error
Error 7 Property or indexer 'System.Windows.Forms.DataGridViewCell.RowIndex' cannot be assigned to -- it is read only
Does anyone know how to fix this error ? searching online hasn't givin a solution
You are trying to change a SelectedCell's row index, which is read-only. If you are trying to change the selected row, you need to set the SelectedIndex for the DataGrid.
DashBoard_DataGrid.SelectedIndex = dr.Cells[i].RowIndex;
Also, try changing SelectedCells to SelectedRows.
try this
.
DashBoard_DataGrid.ClearSelection();
DashBoard_DataGrid.Rows[3].Selected = true;
or if you want to select a specific cell, then
DashBoard_DataGrid.ClearSelection();
DashBoard_DataGrid[0, i].Selected = true;
this will select the first column of the desired row..

How to replace user control in cell into the Grid. WPF?

I have a Grid with 5 rows and 5 columns. I creating this Grid dynamically. Every cell contains custom user control. I would like to replace the user control dynamically with other user control at given row and column. You can see the method implementation which creates the Grid here.
My question is how to replace the user control at given row and column after the Grid is already created? Sorry if my English is bad!
Thank you in advance!
This function will probably fit your needs
public void ReplaceItemAt(Grid grid, FrameworkElement fe, int row, int col)
{
// clear desired cell
var items = grid.Children
.Where(x => Grid.GetRow(x) == row && Grid.GetColumn(x) == col)
.ToArray();
foreach(var item in items) grid.Children.Remove(item);
// make sure the new item is positioned correctly
Grid.SetRow(fe, row);
Grid.SetColumn(fe, col);
// insert the new item into the grid
grid.Children.Add(fe);
}

Nested columns in silverlight datagrid, nested datagrid

I would like to create datagrid that has nested columns (please look at attached image). Or if possible embed grid into cell.
My objects have many different informations, and based on object type I would like to add additional info in my cell (nested Column in the image), that is divided by columns. Is it possible in silverlight ?
It would be perfect to just insert the whole new grid into cell, if possible.
TIA for any suggestions
Sorry, I read "Grid" 8-)
For datagrid you'll be able to do it with datatemplates.
http://mscoder.wordpress.com/2010/09/11/nested-datagrid-using-silverlight-4-and-wcf/
Leverage the LoadingRow event for your data grid to assign the appropriate datatemplate based on your datacontext.
Similar to my response to:
Enabling/Disabling row in a data grid
You do the following:
private void MyDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
MyDataObjectClass dataContext = (e.Row.DataContext as MyDataObjectClass);
foreach (DataGridColumn col in from cols in MyDataGrid.Columns orderby cols.DisplayIndex select cols)
{
FrameworkElement fe = col.GetCellContent(e.Row);
DataGridCell result = fe.Parent as DataGridCell;
// as an example, find a template column w/ a desired sort member path
if (col is DataGridTemplateColumn && col.SortMemberPath == "x")
{
if (condition1)
{
result.ContentTemplate = (DataTemplate)Resources["NestedGridTemplate1"];
}
else
{
result.ContentTemplate = (DataTemplate)Resources["NestedGridTemplate2"];
}
}
}
}

How do I get the selected row data from a data grid view using SelectedRows?

I have a table that I am displaying in a data grid view control. The user selects a single row from the control and presses a button. I need to retrieve the cells from that row and store them as strings.
Exactly how do I get the data using the SelectedRow method? I've been working on this for several hours and I'm at the end of my rope. Here's an example of something I've tried:
DataGridViewCellCollection selRowData = dataGridView1.SelectedRows[0].Cells;
If I try to access selRowData[x], the return value does not contain my data.
You're close - you need to reference each Cell through its index and return its Value property:
string firstCellValue = dataGridView1.SelectedRows[0].Cells[0].Value;
string secondCellValue = dataGridView1.SelectedRows[0].Cells[1].Value;
etc.
If you want the data and the data is likely bound to an datasource, then might I suggest that you get the key from the selection, and then you can use that to access the data any way you like:
dataGridView.SelectedDataKey.Value;
Try using the Item element of the dgv.
dgvFoo.Item(0, dgvFoo.CurrentRow.Index).Value
That would return the value of the first item. You could put that into a for loop to get them all.
Another option would be to use the SelectedRows collection on the object and iterate through each selected row (or just the one in your case).
Well there is no datagridview Item property..#Jay Riggs solution is better...Following solution also works:
string firstCellValue = dataGridView1[0,dataGridView1.CurrentRow.Index].Value.ToString();
string secondCellValue = dataGridView1[0,dataGridView1.CurrentRow.Index].Value.ToString();
Here 0 is the first column and dataGridView1.CurrentRow.Index is the current Row from where to get value.
Perhaps this is a more suitable solution use the cell values of the row clicked:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > -1)
{
var val = this.dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
}
}

Categories