Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Prevent Focus at Particular Cell of DataGridView

, 15 Oct 2011
Rate this:
Please Sign up or sign in to vote.
Prevent Focus at Particular Cell of DataGridView

Introduction

Sometimes, we need to create an application in which Datagridview doesn’t allow to give functionality to user to put focus on a particular cell. It's a very needed requirement which we face from time to time. Suppose a user has a value and he doesn’t want to make it editable, and wants to prevent it from any focus. In this case, this article might help you.

You Need to Know

Like every control, DataGridView has some by default value like DataGridView navigation model does not have any ability to restrict focus to a specific cell.

To implement functionality to give access to user to prevent cell from focus of users, we need to implement our own navigation logic by overriding the appropriate keyboard, navigation and mouse methods such as DataGridView.OnKeyDown, DataGridView.ProcessDataGridViewKey,DataGridView.SetCurrentCellAddressCore, DataGridView.OnMouseDown.

Let's see an example if you want to prevent user to give focus on second column of DataGridView. Then in this case, you need to drive DataGridView class and override the SetCurrentCellAddressCore and SetSelectedCellCore to accomplish the logic you want to perform.

How It Will Look

You can see that the user is able to focus on almost every column except 1st (NationalIDNumber) Column of DataGridView control.

Animated Image - Preventing Cell of DataGridView

How to Do

Take a look at the given images and code to learn how to perform it.
It's better to create a different class and for it, you need to perform the following steps as shown in the given figure.
Right click on Project name under solution Explorer and then Select Add and then click on Class as shown below:

It will AddNewItem Form where you can select class and then need to name it (class).

Now Select Class from Visual C# Items and enter the Name (Example MyDataGridView.cs) in textbox and then press Add button.
When you press Add button, it will create a new class in your Program under Solution Explorer so after creating class we need to inherit DataGridView class with current class (MyDataGridView).
Take a look how:

and DataGridView class is accessible only when you’ve declared
Windows.Form namespace like.
Note: To access DataGridView class you, need to include System.Window.Form namespace in your program.

Using System.Windows.Forms

and then the entire code of DataGridview class will be:

public class myDataGridView : DataGridView
   {
      private int columnToSkip = -1;
       public int ColumnToSkip
       {
           get { return columnToSkip; }
           set { columnToSkip = value; }
       }

       protected override bool SetCurrentCellAddressCore(int columnIndex, int rowIndex,
       bool setAnchorCellAddress, bool validateCurrentCell, bool throughMouseClick)
       {

           if (columnIndex == this.columnToSkip && this.columnToSkip != -1)
           {
              if (this.columnToSkip == this.ColumnCount - 1)
               {
                  return base.SetCurrentCellAddressCore(0, rowIndex + 1,
                      setAnchorCellAddress, validateCurrentCell, throughMouseClick);
               }
               else
               {
                   if (this.ColumnCount != 0)
                   {
                       return base.SetCurrentCellAddressCore(columnIndex + 1, rowIndex,
                          setAnchorCellAddress, validateCurrentCell, throughMouseClick);
                   }
               }
           }
          return base.SetCurrentCellAddressCore(columnIndex, rowIndex,
               setAnchorCellAddress, validateCurrentCell, throughMouseClick);
       }

       protected override void SetSelectedCellCore
		(int columnIndex, int rowIndex, bool selected)
       {
           if (columnIndex == this.columnToSkip)
           {
              if (this.columnToSkip == this.ColumnCount - 1)
               {
                  base.SetSelectedCellCore(0, rowIndex + 1, selected);
               }
              else
               {
                   if (this.ColumnCount != 0)
                   {
                    base.SetSelectedCellCore(columnIndex + 1, rowIndex, selected);
                   }
               }
           }
          else
           {
              base.SetSelectedCellCore(columnIndex, rowIndex, selected);
           }
      }
   }

When collapsing each and every function of class, the program will look as given below.

Now compile the application once to bring existence of myDataGridView control in toolbox. After one successful execution, it will be shown in Toolbox as given below and then we can drag it from toolbox to Form and use it with some additional functionality.

Now, you need to write query to ” bind DataGridView with your database ” as given below. Here, I am using AdventureWorks database to bind DataGridView, you can see at last two circled lines in which the first line is responsible to bind DataGridview to datasource and the very last line is responsible for skipping value of 1st column of DataGridView. Take a look:

Now Press F5 or compile it to see the effect.
You will notice that every column is accessible except the first column which is bounded with a red circle.

A snapshot of the compiled program

So finally, we learned how we can prevent focusing on particular cell of DataGridView. :)

To get a more practical view, you can download the source code too.
Click Me!! to download the source code.


License

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

Share

About the Author

RaviRanjankr
Software Developer
India India
Microsoft Student Partner | CS Student | MCTS | CP MVP | Crazy Learner | Dreamer
 
An Indian, who loves his country, believes in freedom, He is an enthusiast Techie and crazy learner. He is passionate about Technologies and social media. He holds bachelor degree of CS in Information Technology and now pursuing Master degree in Computer Application.
 
He always excited and keen Interested in learning and sharing knowledge. He loves to write blog, learn new things, listen music, taking arts and Playing Games..
 
He keep himself on the desk of his imagination, hanging around with some inceptions.
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionHow to Prevent focus Multhiple colums Pinmembervempulurimuralikrishna13-Dec-12 2:32 
QuestionMulti column Pinmemberfadi77_net23-Oct-12 20:16 
GeneralMy Vote of 5 PinmemberMDNadeemAkhter20-Nov-11 20:02 
GeneralRe: My Vote of 5 PinmemberRaviRanjankr20-Nov-11 20:04 
GeneralGood start Pinmvpthatraja23-Oct-11 21:25 
GeneralRe: Good start PinmemberRaviRanjankr25-Oct-11 8:23 
GeneralRe: Good start Pinmvpthatraja29-Jan-12 9:36 
GeneralRe: Good start PinmvpRaviRanjankr30-Jan-12 23:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 15 Oct 2011
Article Copyright 2011 by RaviRanjankr
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid