Click here to Skip to main content
16,016,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Below is the code to set focus to a particular cell in gridview, but its not working.

dtEmployeeDocumentDetails = objEmployeeMasterBusiness.GetAllEmployeeDocumentDetails();
DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();
gvEmpDocDetails.Columns.Add(chk);
chk.HeaderText = "Select";
chk.Name = "chkselect";
gvEmpDocDetails.AllowUserToAddRows = false;
gvEmpDocDetails.DataSource = dtEmployeeDocumentDetails;
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
btn.Name = "btnDeleteEmpDocument";
btn.HeaderText = "Delete";
gvEmpDocDetails.Columns.Add(btn);
gvEmpDocDetails.Columns[1].Visible = false;
gvEmpDocDetails.Columns[4].Visible = false;
gvEmpDocDetails.Columns[5].Visible = false;
gvEmpDocDetails.Columns[6].Visible = false;
gvEmpDocDetails.Columns[8].Visible = false;
gvEmpDocDetails.Columns[12].Visible = false;
gvEmpDocDetails.Rows[2].Cells[0].Selected = true;

Can you please let me know how to set focus to a cell so that the code written in my cell click event works fine when formloads.

Thanks.
Posted
Updated 19-Aug-17 6:58am

First of all, there is no a focus on a cell. Focus is always a keyboard focus; this is the attribute of a control, not any of its parts. What you need is selection, which is not related to focus.

Also, the result of selection depends on selection style of your DataGridView. Please see DataGridViewSelectionMode:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.selectionmode.aspx[^],
http://msdn.microsoft.com/en-us/library/3c89df86.aspx[^].

You will need System.Windows.Forms.DataGridViewSelectionMode.CellSelect.

—SA
 
Share this answer
 
There is another simple method to select the cell. by setting the dataGridView.CurrentCell.
eg;
C#
this.dataGridView1.CurrentCell = this.dataGridView1.Rows[1].Cells[2];
 
Share this answer
 
Comments
Prathap Gangireddy 31-Dec-12 3:40am    
Hi Jibesh,

I tried in the Form load event...but its not working..still the Firstrow ..FirstColumn cell is selected..
Jibesh 31-Dec-12 4:16am    
was it called after all the rows are loaded to the grid?
Jibesh 31-Dec-12 5:29am    
I tried the same code and it works fine. I called this method in Form_Load event after assigning the dataTable as datasource to dgv.
Jayashree BG 31-Oct-22 2:54am    
Using currentcell, cannot set to intended row.. row is setting to next row of intended one
Grid1.Focus()
 Grid1.CurrentCell = Grid1.Rows(1).Cells(3)
 
Share this answer
 
Comments
CHill60 20-Aug-17 7:41am    
The question was asked and answered over 4 years ago. You have added nothing new to this thread

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