Prevent Focus at Particular Cell of DataGridView-2

The blog is related to one of my previous blog Prevent Focus at Particular Cell of DataGridView.

Few days back, I got an email by a buddy name David querying on same topic ( Prevent Focus at particular Cell of DataGridView). we discussed via email. but after getting one more similar question by reader. so I decided to expose important part of our discussion publicly.

David to Me :
I’m using source code provided at your page
It works ok except when I create a datagridview (using your class) bind to a source and I want to not being selected the first column. When datagridview is viewed, the first column is selected and when I edit it, it begins a no end loop that goes to

Protected Overrides Sub SetSelectedCellCore(columnIndex As Integer, rowIndex As Integer, selected As Boolean)

When I do the same , but selecting the first row second column programmatically after binding to datasource, it works ok. The only rare thing is that when I select a new row it adds another new row and focus goes to that (to the second column).
What can I do for prevent that?

after getting email of David I was little bit because he showed his interest in my article.

My response to David

This article is generally giving some Ideas for enabling user to set functionality to prevent particular cell of DataGridView while DataBinding.
I tried to read your point of view over this article and able to gather your some needed requirement.

Lets See some happening Facts

When you select any Column of DataGridView, a defined SetSelectedCellCore function comes in existence which responsible to Display Selected Cell as Highlighted (Blue Default Color).
the weired thing is that when we select Prevent Column the Selection goes to its next Column. As Example :- when Column 1 is set as Prevention Column and then when we select Column 1 the Highlight Column will be its Corresponding Cell of Column 2. you can remove this problem via minor updating of SetSelectedCellCore(int columnIndex, int rowIndex, bool selected)function.
take a look below how to solve it.

protected override void SetSelectedCellCore(int columnIndex, int rowIndex, bool selected)
            if (columnIndex == this.columnToSkip)
               if (this.columnToSkip == this.ColumnCount - 1)
                   base.SetSelectedCellCore(columnIndex, rowIndex+1, false);  // Updated here last one was base.SetSelectedCellCore(0, rowIndex + 1, selected);
                    if (this.ColumnCount != 0)
                     base.SetSelectedCellCore(columnIndex, 0, false);  // updated here last one was  base.SetSelectedCellCore(columnIndex + 1, rowIndex, selected);
               base.SetSelectedCellCore(columnIndex, rowIndex, selected);

Continue to my response..
Try to View an animated Attached Image- “Prevent Focus on DataGridView.gif” [you can find the animated image at bottom of this article..:D ]

Now when you will add new value its will never loose it Focus. Except Prevention Cell every cell have capability to Display Color (Blue)

In simple the prevented Column works as Readonly mode.

Note :- when your Intention is to add value without Entering value the you need to do some stuff at DefaultValuesNeeded and CellBeginEdit function. but the important point is The Prevent Column will not going to freeze this time. it will store value. [ apart it it works same as before ]

Might be I am getting your question wrong ! if so then please Try to revert back here. I will wait for your Feedback.
You are always welcome

and then genius David checked my code and do some changes as per his requirement and then send back to me. what he replied have a look below

Thank you for your help.
I’ve done another change to your routine for working ok to me.
With your patch focus where ok (but no showing blue the cell)
Here is my class:

Option Strict On
Option Explicit On

Public Class MiDatagridView
Inherits System.Windows.Forms.DataGridView

” usa
” cambia el enter por el tab
”tambien usa
” para evitar que se seleccione determinada columna. Añadidas 2 lineas a esta parte y cambiado una para que vaya ok

Private _ColumnToSkip As Integer = -1

    Protected Overrides Function ProcessDataGridViewKey(e As KeyEventArgs) As Boolean

        If (e.KeyCode = Keys.Enter) Then

            Return True
        End If
        Return MyBase.ProcessDataGridViewKey(e)
    End Function

    Protected Overrides Function ProcessDialogKey(keyData As Keys) As Boolean

        If (keyData = Keys.Enter) Then

            Return True
        End If
        Return MyBase.ProcessDialogKey(keyData)
    End Function

    Public Property ColumnToSkip As Integer
            Return _ColumnToSkip
        End Get
        Set(value As Integer)
            _ColumnToSkip = value
        End Set
    End Property

    Protected Overrides Function SetCurrentCellAddressCore(columnIndex As Integer, rowIndex As Integer, setAnchorCellAddress As Boolean, validateCurrentCell As Boolean, throughMouseClick As Boolean) As Boolean

        If ((columnIndex = Me._ColumnToSkip) And (Me._ColumnToSkip <> -1)) Then

            If (Me._ColumnToSkip = Me.ColumnCount - 1) Then

                Return MyBase.SetCurrentCellAddressCore(0, rowIndex + 1, _
                    setAnchorCellAddress, validateCurrentCell, throughMouseClick)

                If (Me.ColumnCount <> 0) Then

                    Return MyBase.SetCurrentCellAddressCore(columnIndex + 1, rowIndex, _
                       setAnchorCellAddress, validateCurrentCell, throughMouseClick)
                End If
            End If
        End If

        Return MyBase.SetCurrentCellAddressCore(columnIndex, rowIndex, _
             setAnchorCellAddress, validateCurrentCell, throughMouseClick)
    End Function

    Protected Overrides Sub SetSelectedCellCore(columnIndex As Integer, rowIndex As Integer, selected As Boolean)
        If (columnIndex = Me._ColumnToSkip) Then

            If (Me._ColumnToSkip = Me.ColumnCount - 1) Then
                'anteriormente : mybase.setselectedcellcore(0,rowindex+1,selected)
                'por contestacion de e-mail del autor (
                'esta linea se ha cambiado
                MyBase.SetSelectedCellCore(columnIndex, rowIndex + 1, False)
                'esta linea es mia
                MyBase.SetSelectedCellCore(columnIndex + 1, rowIndex + 1, True)
                If (Me.ColumnCount <> 0) Then
                    'anteriormente: MyBase.SetSelectedCellCore(columnIndex + 1, rowIndex, selected)
                    'esta linea es mia
                    MyBase.SetSelectedCellCore(columnIndex, rowIndex, False)
                    'esta linea es mia
                    MyBase.SetSelectedCellCore(columnIndex + 1, rowIndex, True)
               End If
            End If
            MyBase.SetSelectedCellCore(columnIndex, rowIndex, selected)
        End If
    End Sub
 End Class

That class implements your code with 2 lines added and one changed.
It adds functionality for when you are editing a cell in a datagridview and press enter it acts like pressing tab. Focus does not go to row below, it goes to column of the right (functions ProcessDialogKey and ProcessDataGridViewKey).

Thank you.



About Ravi Ranjan Kumar

An Indian who Living, Loving & Learning Technology with different tastes and willing to share knowledge and thoughts.
This entry was posted in .Net, C# and tagged , , . Bookmark the permalink.

3 Responses to Prevent Focus at Particular Cell of DataGridView-2

  1. I dont know what to say. This weblog is amazing. Thats not truly a truly huge statement, but its all I could come up with following reading this. You know so much about this subject. So a lot so that you created me need to understand much more about it. Your weblog is my stepping stone, my friend. Thanks for the heads up on this subject.

  2. says:

    What i do not understood is in truth how you’re not actually much more well-favored than you may be right now. You are so intelligent. You know thus significantly in relation to this matter, made me in my view believe it from so many varied angles. Its like women and men don’t seem to be interested except it is something to do with Lady gaga! Your own stuffs nice. At all times care for it up!

  3. Abhi says:

    dedication showing here. gone through your previous article. nice one

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s