Binuriki Cliean Jay
Binuriki Cliean Jay

Reputation: 98

wpf datagrid select first cell programmatically

my datagrid SelectionMode="Single", I need to switch the cell focus on the first cell whenever I click a cell in the Description column or any other column.

this is my code that I attempted to

private void dgvConfig_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        DependencyObject dep = (DependencyObject)e.OriginalSource;
        // iteratively traverse the visual tree
        while ((dep != null) &&
                !(dep is DataGridCell) &&
                !(dep is DataGridColumnHeader))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }

        if (dep == null)
            return;

        if (dep is DataGridColumnHeader)
        {
            string columnHead = "";
            DataGridColumnHeader columnHeader = dep as DataGridColumnHeader;
            columnHead = columnHeader.Column.Header.ToString();
            LoadGridview(columnHead);
            //MessageBox.Show(columnHeader.Column.DisplayIndex.ToString());
        }

        if (dep is DataGridCell)
        {
            DataGridCell cell = dep as DataGridCell;
            string cellName = cell.Column.Header.ToString();

            if (cellName.Equals("Description"))
            {


                cell.Focus();
                string datagridselect;
                //datagridselect = DataGrid.SelectedIndexProperty[]
                //var cellInfo = dgvConfig.SelectedCells[0];
                //var xt = dgvConfig.CurrentCell.Column.

                // the prob is I cant seem to access an array to move the focus to the first column of that selected row


            }

        }


    }

Upvotes: 2

Views: 1311

Answers (1)

Rang
Rang

Reputation: 1372

Have a try:

 private void dgShow_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        foreach(DataGridCellInfo info in dgShow.SelectedCells)
        {
           if( info.Column.Header.ToString()=="Name")
           {
               dgShow.CurrentCell = info;
               break;
           }
        }
    }

Upvotes: 1

Related Questions