Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hai

I have a Datagrid called Dg and I want to programatically change row and column.

I use this code

Dg.CurrentCell = New DataGridCellInfo(Dg.Items(IntRow), Dg.Columns(IntCol))
for setting the current cell and this is working fine but the blue color of selected cell stands in the same cell. Please tell me how to move this focus along with the current cell.

I don't to make Dg.SelectedCells.Clear() as this removes only selection color and not focus.


Thanks
Posted

1 solution

Hi use the following code,

C#
DataGridCell objCellToFocus = DataGridExtensions.GetCell(Dg,(DataGridRow)Dg.ItemContainerGenerator.ContainerFromIndex(1), 2);
            objCellToFocus.Focus();

C#
public static class DataGridExtensions
    {
        public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int columnIndex = 0)
        {
            if (row == null) return null;

            var presenter = FindVisualChild<datagridcellspresenter>(row);
            if (presenter == null) return null;

            var cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
            if (cell != null) return cell;

            // now try to bring into view and retreive the cell
            grid.ScrollIntoView(row, grid.Columns[columnIndex]);
            cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);

            return cell;
        }

        public static IEnumerable<t> FindVisualChildren<t>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && child is T)
                    {
                        yield return (T)child;
                    }

                    foreach (T childOfChild in FindVisualChildren<t>(child))
                    {
                        yield return childOfChild;
                    }
                }
            }
        }

        public static childItem FindVisualChild<childitem>(DependencyObject obj) where childItem : DependencyObject
        {
            foreach (childItem child in FindVisualChildren<childitem>(obj))
            {
                return child;
            }

            return null;
        }
    }
</childitem></childitem></t></t></t></datagridcellspresenter>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900