• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 589
  • Last Modified:

Disabling cell (0,0) focus on initial load of DataGrid

I have a DataGrid built in VB.Net.

This form\datagrid has users select rows they'd like to update via a button click event handler.

The initial load of the form populates via a bind of the datagrid to a dataset that's filled.
 
I'd like the form to load and have the datagrid display rows but not have any row or cell highlighted (focused on).  Currently the form always has row 0, cell 0 highlighted.

Like to find a way to have datagrid populate with no rows or cell selected.

Thanks,
Jon
0
JMO9966
Asked:
JMO9966
  • 3
  • 2
1 Solution
 
SanclerCommented:
0
 
JMO9966Author Commented:
Thanks, but it didn't seem to work.  I kept getting a statement cannot appear within a method body on the public Sub SetNoCurrentCell.

I also already have a public Class frmMain so I got an error when I tried to add inherits DataGrid in my class since I'm already inheriting System.Windows.Forms.

Any thoughts?  Here's the code I tried

Public Class MyDataGrid
 
     Inherits DataGrid
      Public WM_LBUTTONDOWN As Integer = 513
      Public WM_LBUTTONUP As Integer = 514
 
     Shared _
     Function SendMessage(hWnd As IntPtr, msg As Int32, wParam As Int32, lParam As Int32) As Boolean
 
     Public Sub SetNoCurrentCell()
 
     'click on top left corner of the grid
 
     SendMessage(Me.Handle, WM_LBUTTONDOWN, 0, 0)
     SendMessage(Me.Handle, WM_LBUTTONUP, 0, 0)
 
     End Sub 'SetNoCurrentCell
 
End Class 'MyDataGrid




Here's my code for my program:


Option Explicit On

Imports System
Imports System.Data
Imports System.Data.OleDb
Imports System.String
Imports ADODB
Imports System.Windows.Forms.ScrollableControl
Imports System.IO
Imports System.Text


Public Class frmMain
    Inherits System.Windows.Forms.Form


    Private dsJB_User As New DataSet
    Private tblJB_user As DataTable
    Private rs As New Recordset
    Private daJB_User As New Odbc.OdbcDataAdapter
    'Private dcJB_User As New Odbc.OdbcConnection
    Private objConn As New ADODB.Connection
    Private sSQL As String
    Private Const adCmdText As Integer = 1
    Private adEditAdd As Integer = 2

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents dgJB_User As System.Windows.Forms.DataGrid
    Friend WithEvents btnClearUser As System.Windows.Forms.Button
    Friend WithEvents btnExit As System.Windows.Forms.Button
    Friend WithEvents mmuFile As System.Windows.Forms.MainMenu
    Friend WithEvents MenuItem1 As System.Windows.Forms.MenuItem
    Friend WithEvents mmuFileExit As System.Windows.Forms.MenuItem
    Friend WithEvents mmuClearUser As System.Windows.Forms.MenuItem
    Friend WithEvents lblPromptKeystrokes As System.Windows.Forms.Label
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.dgJB_User = New System.Windows.Forms.DataGrid
        Me.btnClearUser = New System.Windows.Forms.Button
        Me.lblPromptKeystrokes = New System.Windows.Forms.Label
        Me.btnExit = New System.Windows.Forms.Button
        Me.mmuFile = New System.Windows.Forms.MainMenu
        Me.MenuItem1 = New System.Windows.Forms.MenuItem
        Me.mmuClearUser = New System.Windows.Forms.MenuItem
        Me.mmuFileExit = New System.Windows.Forms.MenuItem
        CType(Me.dgJB_User, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'dgJB_User
        '
        Me.dgJB_User.CaptionFont = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.dgJB_User.CaptionText = "Who's currently using a JobBOSS Seat License"
        Me.dgJB_User.DataMember = ""
        Me.dgJB_User.HeaderForeColor = System.Drawing.SystemColors.ControlText
        Me.dgJB_User.Location = New System.Drawing.Point(200, 24)
        Me.dgJB_User.Name = "dgJB_User"
        Me.dgJB_User.PreferredColumnWidth = 250
        Me.dgJB_User.Size = New System.Drawing.Size(536, 288)
        Me.dgJB_User.TabIndex = 0
        '
        'btnClearUser
        '
        Me.btnClearUser.Font = New System.Drawing.Font("Microsoft Sans Serif", 14.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnClearUser.ForeColor = System.Drawing.Color.Blue
        Me.btnClearUser.Location = New System.Drawing.Point(392, 336)
        Me.btnClearUser.Name = "btnClearUser"
        Me.btnClearUser.Size = New System.Drawing.Size(136, 48)
        Me.btnClearUser.TabIndex = 1
        Me.btnClearUser.Text = "Clear User"
        '
        'lblPromptKeystrokes
        '
        Me.lblPromptKeystrokes.BackColor = System.Drawing.Color.Silver
        Me.lblPromptKeystrokes.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblPromptKeystrokes.ForeColor = System.Drawing.Color.Black
        Me.lblPromptKeystrokes.Location = New System.Drawing.Point(48, 104)
        Me.lblPromptKeystrokes.Name = "lblPromptKeystrokes"
        Me.lblPromptKeystrokes.Size = New System.Drawing.Size(100, 112)
        Me.lblPromptKeystrokes.TabIndex = 3
        Me.lblPromptKeystrokes.Text = "CTRL or SHIFT key to select multiple users."
        '
        'btnExit
        '
        Me.btnExit.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnExit.ForeColor = System.Drawing.Color.Black
        Me.btnExit.Location = New System.Drawing.Point(392, 408)
        Me.btnExit.Name = "btnExit"
        Me.btnExit.Size = New System.Drawing.Size(136, 48)
        Me.btnExit.TabIndex = 4
        Me.btnExit.Text = "Exit"
        '
        'mmuFile
        '
        Me.mmuFile.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuItem1})
        '
        'MenuItem1
        '
        Me.MenuItem1.Index = 0
        Me.MenuItem1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mmuClearUser, Me.mmuFileExit})
        Me.MenuItem1.Text = "File"
        '
        'mmuClearUser
        '
        Me.mmuClearUser.Index = 0
        Me.mmuClearUser.Shortcut = System.Windows.Forms.Shortcut.CtrlC
        Me.mmuClearUser.Text = "&Clear User"
        '
        'mmuFileExit
        '
        Me.mmuFileExit.Index = 1
        Me.mmuFileExit.Shortcut = System.Windows.Forms.Shortcut.CtrlX
        Me.mmuFileExit.Text = "E&xit"
        '
        'frmMain
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(848, 481)
        Me.Controls.Add(Me.btnExit)
        Me.Controls.Add(Me.lblPromptKeystrokes)
        Me.Controls.Add(Me.btnClearUser)
        Me.Controls.Add(Me.dgJB_User)
        Me.ForeColor = System.Drawing.Color.Blue
        Me.Menu = Me.mmuFile
        Me.Name = "frmMain"
        Me.Text = "JobBOSS Clear User Utility"
        CType(Me.dgJB_User, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim path As String = "jbclr.txt"
        Dim pstrLine, pstrFile As String
        Dim sr As StreamReader
        Dim sw As StreamWriter
        Dim fs As FileStream
        Dim input As Integer
        Dim last As String
        Dim newcount As Integer = 0
        Dim rows As Integer = 0


        ' Determine if file exists.
        If File.Exists(path) Then

            sr = File.OpenText(path)
            input = sr.ReadLine()
            newcount = input + 1

            If newcount > 10 Then
                Me.Close()
            End If

            sr.Close()

        Else

            ' Create the file.
            fs = File.Create(path)
            fs.Close()

            ' Add some information to the file.
            sw = New System.IO.StreamWriter(path)
            sw.Write(newcount)

        End If

        'sw.WriteLine(newcount)
        sw = New System.IO.StreamWriter(path)
        sw.Write(newcount)
        sw.Close()

        Dim tblJB_User As New DataTable
        Dim grdJB_User As DataGrid

        Const adStateOpen As Integer = 1
        Const adOpenStatic As Integer = 3
        Const adLockBatchOptimistic As Integer = 4
        Const adCmdText As Integer = 1
        Const adEditAdd As Integer = 2


        Try

            BindData()
        Catch ex As Exception
            Application.Exit()
        End Try
        'setnocurrentcell()


    End Sub

    Private Sub btnClearUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearUser.Click

        Dim intRows As Integer = 0
        Dim currentRow As Integer = 0
        Dim drCurrent As DataRow
        Dim intCount As Integer = 0
        Dim count As Integer = 0
        Dim intSelect As Integer = 0
        Dim intFor As Integer = 0


        tblJB_user = dsJB_User.Tables("JB_User")

        'Loop through DataSet to find selected records
        intRows = tblJB_user.Rows.Count()

        Dim dcJB_User As Odbc.OdbcConnection = New Odbc.OdbcConnection("DSN=jbidx2k;uid=jobboss;pwd=Bali")
        dcJB_User.Open()
        For i As Int32 = 0 To tblJB_user.Rows.Count - 1


            If dgJB_User.IsSelected(i) Then
                intSelect = 1

                sSQL = "UPDATE JB_User set Log_Number = 0, Machine_Name = ' ' where UserID = '" & tblJB_user.Rows(i)("UserID") & "'"
                Dim cmd As Odbc.OdbcCommand = New Odbc.OdbcCommand(sSQL)
                cmd.Connection = dcJB_User
                cmd.ExecuteNonQuery()

            End If

        Next
        dcJB_User.Close()
        BindData()


        If intSelect = 0 Then
            MessageBox.Show("No records selected.  Use far left column to select records.")
            Exit Sub
        End If

    End Sub

    Private Function CreateTableStyle() As DataGridTableStyle
        Dim cTableStyle As DataGridTableStyle = New DataGridTableStyle

        Dim tcol1 As DataGridTextBoxColumn = New DataGridTextBoxColumn
        tcol1.HeaderText = "User ID"
        tcol1.MappingName = "UserID"
        tcol1.Width = 248
        cTableStyle.GridColumnStyles.Add(tcol1)

        Dim tcol2 As DataGridTextBoxColumn = New DataGridTextBoxColumn
        With tcol2
            .HeaderText = "User Name"
            .MappingName = "User_Name"
            .Width = 248

        End With
        cTableStyle.GridColumnStyles.Add(tcol2)
        cTableStyle.MappingName = "JB_User"

        Return cTableStyle
    End Function

    Private Sub BindData()
        Try
            dsJB_User.Clear()

            sSQL = "Select UserID, User_Name, Log_Number, Machine_Name from JB_User where Log_Number > 0 order by UserID;"
            Dim dcJB_User As Odbc.OdbcConnection = New Odbc.OdbcConnection("DSN=jbidx2k;uid=jobboss;pwd=Bali")

            daJB_User.SelectCommand = New Odbc.OdbcCommand(sSQL, dcJB_User)

            daJB_User.Fill(dsJB_User, "JB_User")


            If dsJB_User.Tables(0).Rows.Count = 0 Then
                MsgBox("No Current Users, Exit Utility.")
                'Application.Exit
                Application.Exit()
            End If

            dgJB_User.TableStyles.Clear()
            dgJB_User.TableStyles.Add(Me.CreateTableStyle)

            dgJB_User.DataSource = dsJB_User.Tables(0)
            dgJB_User.ReadOnly = True



        Catch ex As Exception
            MessageBox.Show("Failed to connect to JBIDX2K. Ensure ODBC setup correct for JBIDX2K DSN.")
            Throw
        End Try


    End Sub

    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        Me.Close()

    End Sub


    Private Sub mmuFileExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mmuFileExit.Click
        Me.Close()

    End Sub


    Private Sub dgJB_User_MouseUp(ByVal sender As System.Object, _
        ByVal e As System.Windows.Forms.MouseEventArgs) _
        Handles dgJB_User.MouseUp

        Dim pt As New Point(e.X, e.Y)
        Dim hti As DataGrid.HitTestInfo = dgJB_User.HitTest(pt)

        If hti.Type = Windows.Forms.DataGrid.HitTestType.Cell Then
            dgJB_User.Select(hti.Row)
        End If
    End Sub


    Private Sub mmuClearUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mmuClearUser.Click

        Dim intRows As Integer = 0
        Dim currentRow As Integer = 0
        Dim drCurrent As DataRow
        Dim intCount As Integer = 0
        Dim count As Integer = 0
        Dim intSelect As Integer = 0
        Dim intFor As Integer = 0


        tblJB_user = dsJB_User.Tables("JB_User")

        'Loop through DataSet to find selected records
        intRows = tblJB_user.Rows.Count()

        Dim dcJB_User As Odbc.OdbcConnection = New Odbc.OdbcConnection("DSN=jbidx2k;uid=jobboss;pwd=Bali")
        dcJB_User.Open()
        For i As Int32 = 0 To tblJB_user.Rows.Count - 1


            If dgJB_User.IsSelected(i) Then
                intSelect = 1

                sSQL = "UPDATE JB_User set Log_Number = 0, Machine_Name = ' ' where UserID = '" & tblJB_user.Rows(i)("UserID") & "'"
                Dim cmd As Odbc.OdbcCommand = New Odbc.OdbcCommand(sSQL)
                cmd.Connection = dcJB_User
                cmd.ExecuteNonQuery()

            End If

        Next
        dcJB_User.Close()
        BindData()


        If intSelect = 0 Then
            MessageBox.Show("No records selected.  Use far left column to select records.")
            Exit Sub
        End If

    End Sub

End Class
 
0
 
SanclerCommented:
First the good news.  The reported error in the datagrid code can be overcome by changing this line

    Shared _
    Function SendMessage(ByVal hWnd As IntPtr, ByVal msg As Int32, ByVal wParam As Int32, ByVal lParam As Int32) As Boolean

to this

    Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As IntPtr, ByVal msg As Int32, ByVal wParam As Int32, ByVal lParam As String) As Boolean

Now the bad news.  It's not working for me, either.  It looks as though it should, but it isn't.  And I haven't got time at the moment to find out why.

But if your objective really is just to avoid the highlighting of the top left cell ON INITIAL LOADING you can do this by changing the focus to some other control immediately after the data is loaded.  The highlight that you don't want only shows when the datagrid has the focus.

Roger
0
 
JMO9966Author Commented:
Thanks Roger,
 
I tried setting focus on one of my buttons, but that isn't working either.
 
I added this line in a few different spots after the datagrid loads, but it didn't make a difference.
 
btnClearUser.focus()

Can't figure out why that doesn't work either??

Thanks,
Jon M
0
 
SanclerCommented:
It's because of this line

        Me.dgJB_User.TabIndex = 0

I assume the "few different spots" in which you put

        btnClearUser.focus()

were all still in the Form_Load event.  That's probably my fault, as I did say "immediately after the data is loaded" ;-(

But what then happened was the Form_Activated event fired and simply re-moved the focus to the first control in the tab order.  So, there are two possible solutions.  One is to move

        btnClearUser.focus()

into the Activated, rather than the Load, sub.  The other, perhaps neater, one is to change the TabIndex of the controls so that

        Me.dgJB_User.TabIndex = 1

and

        Me.btnClearUser.TabIndex = 0

which will start the form off with focus set to btnClearUser without the need for any additional code.  If you're apprehensive, in the light of the "Do not modify it using the code editor" warning, of making changes in the "Windows Form Designer generated code" Region, you can change controls' TabIndex properties in the Properties Pane in Design View, or from the Tab Order item on the View menu.

Incidentally, although I haven't re-checked and I didn't think about it at the time, that's probably why the code I pointed you to in the first instance appeared not to work.

Roger
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now