473,554 Members | 2,936 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

DataGrid Row selection in a VB Form

I am using code from Help with two exceptions. (1) I increased the number of sample rows from 3 to 20, and (2) I anchored the datagrid to bottom of form so that I can change the size of the grid by changing the size of the form

The code is at the following location in the January, 2004 help

ms-help://MS.VSCC.2003/MS.MSDNQTR.2004 JAN.1033/cpref/html/frlrfSystemWind owsFormsDataGri dClassTopic.ht

You can also find it by doing a search for "DataGrid Class", titles search only. It should show up as Rank #1

The problem occurs when I select a row at the bottom of the grid that is only 80% or so exposed height wise. If I select, Row1, the Debug window indicates that I selected Row #0 as I would expect. The same is true with I select any other row as long as it is fully displayed vertically in the grid.

If I select Row #10 that is only 50% exposed, instead of seeing Row = 9 in the debug window as I would expect, I see Row = 10. Needless to say this behavior is a problem when processing the selected row. Is there a workaround? One solution would be to only display complete rows in the grid rather than partial rows but I can't find a way to do it

For convenience, I am listing my entire code below, you can either paste it into a new form or start with code from help and make the two changes. Thank you very much for any assistance that you can provide

=============== ==============

Option Explicit On
Option Strict O

Imports Syste
Imports System.Componen tMode
Imports System.Dat
Imports System.Drawin
Imports System.Windows. Form

Public Class Form
Inherits System.Windows. Forms.For
Private components As System.Componen tModel.Containe
Private WithEvents button1 As Butto
Private WithEvents button2 As Butto
Private WithEvents myDataGrid As DataGri
Private myDataSet As DataSe
Private TablesAlreadyAd ded As Boolea

Public Sub New(
' Required for Windows Form Designer support
InitializeCompo nent(
' Call SetUp to bind the controls
End Su

Private Sub InitializeCompo nent(
Me.button1 = New System.Windows. Forms.Butto
Me.button2 = New System.Windows. Forms.Butto
Me.myDataGrid = New System.Windows. Forms.DataGri
CType(Me.myData Grid, System.Componen tModel.ISupport Initialize).Beg inInit(
Me.SuspendLayou t(


Me.button1.Loca tion = New System.Drawing. Point(24, 16
Me.button1.Name = "button1
Me.button1.Size = New System.Drawing. Size(120, 24
Me.button1.TabI ndex =
Me.button1.Text = "Change Appearance


Me.button2.Loca tion = New System.Drawing. Point(150, 16
Me.button2.Name = "button2
Me.button2.Size = New System.Drawing. Size(120, 24
Me.button2.TabI ndex =
Me.button2.Text = "Get Binding Manager


Me.myDataGrid.A nchor = CType(((System. Windows.Forms.A nchorStyles.Top Or System.Windows. Forms.AnchorSty les.Bottom)
Or System.Windows. Forms.AnchorSty les.Left), System.Windows. Forms.AnchorSty les
Me.myDataGrid.C aptionText = "Microsoft DataGrid Control
Me.myDataGrid.D ataMember = "
Me.myDataGrid.H eaderForeColor = System.Drawing. SystemColors.Co ntrolTex
Me.myDataGrid.L ocation = New System.Drawing. Point(24, 50
Me.myDataGrid.N ame = "myDataGrid
Me.myDataGrid.S ize = New System.Drawing. Size(300, 200
Me.myDataGrid.T abIndex =


Me.AutoScaleBas eSize = New System.Drawing. Size(5, 13
Me.ClientSize = New System.Drawing. Size(450, 330
Me.Controls.Add (Me.button1
Me.Controls.Add (Me.button2
Me.Controls.Add (Me.myDataGrid
Me.Name = "Form1
Me.Text = "DataGrid Control Sample
CType(Me.myData Grid, System.Componen tModel.ISupport Initialize).End Init(
Me.ResumeLayout (False

End Su

Public Shared Sub Main(
Application.Run (New Form1
End Su

Private Sub SetUp(
' Create a DataSet with two tables and one relation
' Bind the DataGrid to the DataSet. The dataMembe
' specifies that the Customers table should be displayed
myDataGrid.SetD ataBinding(myDa taSet, "Customers"
End Su

Protected Sub button1_Click(B yVal sender As System.Object, ByVal e As System.EventArg s) Handles button1.Clic
If TablesAlreadyAd ded = True Then Exit Sub
AddCustomDataTa bleStyle()
End Sub

Private Sub AddCustomDataTa bleStyle()
Dim ts1 As New DataGridTableSt yle
ts1.MappingName = "Customers"
' Set other properties.
ts1.Alternating BackColor = Color.LightGray
' Add a GridColumnStyle and set its MappingName
' to the name of a DataColumn in the DataTable.
' Set the HeaderText and Width properties.

Dim boolCol As New DataGridBoolCol umn
boolCol.Mapping Name = "Current"
boolCol.HeaderT ext = "IsCurrent Customer"
boolCol.Width = 150
ts1.GridColumnS tyles.Add(boolC ol)

' Add a second column style.
Dim TextCol As New DataGridTextBox Column
TextCol.Mapping Name = "custName"
TextCol.HeaderT ext = "Customer Name"
TextCol.Width = 250
ts1.GridColumnS tyles.Add(TextC ol)

' Create the second table style with columns.
Dim ts2 As New DataGridTableSt yle
ts2.MappingName = "Orders"

' Set other properties.
ts2.Alternating BackColor = Color.LightBlue

' Create new ColumnStyle objects
Dim cOrderDate As New DataGridTextBox Column
cOrderDate.Mapp ingName = "OrderDate"
cOrderDate.Head erText = "Order Date"
cOrderDate.Widt h = 100
ts2.GridColumnS tyles.Add(cOrde rDate)

' Use a PropertyDescrip tor to create a formatted
' column. First get the PropertyDescrip torCollection
' for the data source and data member.
Dim pcol As PropertyDescrip torCollection = _
Me.BindingConte xt(myDataSet, "Customers.cust ToOrders"). _
GetItemProperti es()

' Create a formatted column using a PropertyDescrip tor.
' The formatting character "c" specifies a currency format. */

Dim csOrderAmount As _
New DataGridTextBox Column(pcol("Or derAmount"), "c", True)
csOrderAmount.M appingName = "OrderAmoun t"
csOrderAmount.H eaderText = "Total"
csOrderAmount.W idth = 100
ts2.GridColumnS tyles.Add(csOrd erAmount)

' Add the DataGridTableSt yle instances to
' the GridTableStyles Collection.
myDataGrid.Tabl eStyles.Add(ts1 )
myDataGrid.Tabl eStyles.Add(ts2 )

' Sets the TablesAlreadyAd ded to true so this doesn't happen again.
TablesAlreadyAd ded = True
End Sub

Protected Sub button2_Click(B yVal sender As System.Object, ByVal e As System.EventArg s) Handles button2.Click
Dim bmGrid As BindingManagerB ase
bmGrid = BindingContext( myDataSet, "Customers" )
MessageBox.Show (("Current BindingManager Position: " & bmGrid.Position ))
End Sub

Private Sub Grid_MouseUp(By Val sender As System.Object, ByVal e As System.Windows. Forms.MouseEven tArgs) Handles myDataGrid.Mous eUp
' Create a HitTestInfo object using the HitTest method.
' Get the DataGrid by casting sender.
Dim myGrid As DataGrid = CType(sender, DataGrid)
Dim myHitInfo As DataGrid.HitTes tInfo = myGrid.HitTest( e.X, e.Y)
Console.WriteLi ne(myHitInfo)
Console.WriteLi ne(myHitInfo.Ty pe)
Console.WriteLi ne(myHitInfo.Ro w)
Console.WriteLi ne(myHitInfo.Co lumn)
End Sub

' Create a DataSet with two tables and populate it.
Private Sub MakeDataSet()
' Create a DataSet.
myDataSet = New DataSet("myData Set")

' Create two DataTables.
Dim tCust As New DataTable("Cust omers")
Dim tOrders As New DataTable("Orde rs")

' Create two columns, and add them to the first table.
Dim cCustID As New DataColumn("Cus tID", GetType(Integer ))
Dim cCustName As New DataColumn("Cus tName")
Dim cCurrent As New DataColumn("Cur rent", GetType(Boolean ))
tCust.Columns.A dd(cCustID)
tCust.Columns.A dd(cCustName)
tCust.Columns.A dd(cCurrent)

' Create three columns, and add them to the second table.
Dim cID As New DataColumn("Cus tID", GetType(Integer ))
Dim cOrderDate As New DataColumn("ord erDate", GetType(DateTim e))
Dim cOrderAmount As New DataColumn("Ord erAmount", GetType(Decimal ))
tOrders.Columns .Add(cOrderAmou nt)
tOrders.Columns .Add(cID)
tOrders.Columns .Add(cOrderDate )

' Add the tables to the DataSet.
myDataSet.Table s.Add(tCust)
myDataSet.Table s.Add(tOrders)

' Create a DataRelation, and add it to the DataSet.
Dim dr As New DataRelation("c ustToOrders", cCustID, cID)
myDataSet.Relat ions.Add(dr)

' Populates the tables. For each customer and order,
' creates two DataRow variables.
Dim newRow1 As DataRow
Dim newRow2 As DataRow

' Create three customers in the Customers Table.
Dim i As Integer
For i = 1 To 30
newRow1 = tCust.NewRow()
newRow1("custID ") = i
' Add the row to the Customers table.
tCust.Rows.Add( newRow1)
Next i
' Give each customer a distinct name.
tCust.Rows(0)(" custName") = "Customer1"
tCust.Rows(1)(" custName") = "Customer2"
tCust.Rows(2)(" custName") = "Customer3"

' Give the Current column a value.
tCust.Rows(0)(" Current") = True
tCust.Rows(1)(" Current") = True
tCust.Rows(2)(" Current") = False

' For each customer, create five rows in the Orders table.
For i = 1 To 3
Dim j As Integer
For j = 1 To 5
newRow2 = tOrders.NewRow( )
newRow2("CustID ") = i
newRow2("orderD ate") = New DateTime(2001, i, j * 2)
newRow2("OrderA mount") = i * 10 + j * 0.1
' Add the row to the Orders table.
tOrders.Rows.Ad d(newRow2)
Next j
Next i
End Sub
End Class

Nov 20 '05 #1
5 5896
Hi Genojoe,

I get the answers when I push on the button, that I think there should be,
can you explain again what should be the error?

Nov 20 '05 #2
When I execute this application in Debug, I will initially see about 9.25 rows. To make the debug listing shorter, I remarked out 3 of the 4 Console.WriteLi ne's. If I then click the header records sequentially without scrolling the grid, I get the following listing in Debug

{ RowHeader,0,-1
{ RowHeader,1,-1
{ RowHeader,2,-1
{ RowHeader,3,-1
{ RowHeader,4,-1
{ RowHeader,5,-1
{ RowHeader,6,-1
{ RowHeader,7,-1
{ RowHeader,8,-1
{ RowHeader,10,-1} (record is only partially visible at bottom of page.

The problem occurs at Row #10 because only 25% of it is visible vertically. The last Debug line should be:
{RowHeader,9,-1}. If I scroll the grid with the Vertical scroll bar so that a row is 100% visible before clicking it, there is not a problem. The problem occurs only when a part of the row is hidden at the bottom of the page. The problem occurs if the row is 95% visible

Hope this is clearer. It is a 100% repeatable problem.
Nov 20 '05 #3
Hi GenoJoe,

This code

Console.WriteLi ne(DirectCast(s ender, DataGrid).Curre ntRowIndex)
Console.WriteLi ne(myHitInfo.Ro w)
Console.WriteLi ne(myHitInfo.Co lumn)

gives with me when row 30 is hardly visible and I click on it in the front


While if is is full visible


Was that what you did mean?

Nov 20 '05 #4
You are on the money. I assume you know that you solved my problem. Is it fair to say that Microsoft has a slight quirk in the way it handles the clicking of a partial row? When I look at the Object Browser what I see suggests that Info.Row and Grid.CurrentRow Index should result in the same value. Lines below are from Object browser. The lesson is to use CurrentRowIndex and realize that Info.Row is not accurate in all cases.

Thank you.

Row() As Integer
Gets the number of the row the user has clicked.

CurrentRowIndex () As Integer
Gets or sets index of the selected row.
Nov 20 '05 #5
I have now learned more about this problem. First, my goal was to perform some operations based upon the row header being clicked. My problem was with the sample code. It uses a mouse up event. By changing to a mouse down event, my problem disappeared. If this sample code used the mouse-down event, this series of messages would never have occurred

Regarding using CurrentRowIndex , at first it looked like a good solution. Later I realized that it is not a good solution. If a person clicks the + or - in the row header, the row does not change and reflects the previously selected row and not the clicked row. Not the behavior that I want

Nov 20 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

by: Ashish Shridharan | last post by:
Hi All I have been trying to add a control to the header cell of a datagrid on my ASP.NET page. These controls are defined in the HTML as ASP.NET web controls. They are being added into the header of the datagrid in the "ItemDataBound" method of the grid. However, once, they are added in the grid, i seem to lose the event handler for the...
by: Soul | last post by:
*** I am not sure this question belong to *.languages.csharp or *.framework.windowsdorms.databinding, so I post to both *** Hi, Currently I have a DataGrid which bind to a DataSet. One of the column in the DataSet table consist of DateTime value. I also have two DateTimePicker (startDate and endDate) on my Windows form.
by: Randy | last post by:
Hello, I've got a Form which has a dataGrid on it. In one of the columns of the dataGrid, I've implemented a ComboBox using a DataGridComboBoxColumn Class. I've also over ridden the other columns with a custom DataGridTextBoxColumn class so I can color certain columns. What I'm trying to do is.based on the selection in the ComboBox, I...
by: Wayne | last post by:
I have a datagrid on my windows form, it needs to be read only and when a user selects a row, I want the whole row to be selected. How would I go about doing this? -- Thanks Wayne Sepega Jacksonville, Fl
by: Alpha | last post by:
I have several textboxes that I need to chang the text when the selection row is changed in a datagrid. I have the following code. This textbox displayes the initial selection but when I click on different rows in the datagrid, the textbox content doesn't change to reflect the change. How can I address this? Also, If the user change the...
by: Zachary Hilbun | last post by:
I'm using a DataGrid control in a web form. I can display it using binding but when I click on any of the items there is no feedback that that row has been selected. I changed SelectedItemStyle but the changes do not appear when a row is clicked. What do I need to do to get it to do selection? ...
by: I am Sam | last post by:
I have a rather complicated problem I need to sort out and wonder if anyone can assist me. The ingredients: Two DropDownList Controls One DataGrid Purpose of Page:
by: pmcguire | last post by:
I have a DataGrid control for which I have also created several new extended DataGridColumnStyles. They behave pretty nicely, but I can't figure out how to implement Selected Item formatting for them. In a plain vanilla DataGrid, when you click on the RowHeader, the appropriate row changes colors. I ASSUME this should be done in the Paint...
by: Phillip N Rounds | last post by:
I have a DataGrid in a web form (ASP1.1, C#, VS 2003) that I'm trying to add some functionality to, and I can't figure out how to do int. The existing DataGrid has several databound columns and a Template Columns, into which I put buttons. When the user clicks on the 'Do It' button, the selection is recorded in an underlying database, and...
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.