473,581 Members | 2,224 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

DataGridView Formatting and Filtering

I have a DataGridView which displays numeric (Int32) data from an underlying
database. I want the numbers to be displayed in numeric format "#,###"
(with commas). I want to also limit the user so they can only input
numerical values. Is there any way to do this? Currently my formatting
works but if the user enters a value manually the formatting is not applied
to the new value. Also I haven't found a way to allow only numerical input.
Code is below.

So for example if the underlying value is 13200 once the data is read into
the DataGrid it's displayed as 13,200. If I manually change it and type in
13200 it stays that way, without the comma.

Thanks,
Ryan
Me.DataGridView Details.Columns .Add("Number", "Number")

With Me.DataGridView Details.Columns ("Number")

..DefaultCellSt yle.Format = "#,###"

..DefaultCellSt yle.Alignment = DataGridViewCon tentAlignment.B ottomRight

End With
Jan 4 '07 #1
7 16390
I'm halfway there. Apparently the formatting is not being applied because
the datagrid is viewing the data entered as a string. I added the following
code to the DataGridView_Ce llValueChanged event and it works as expected.
Now to prevent the user from entering anything other than numerical data,
and ideas how to do this? Thanks.
Private Sub DataGridViewDet ails_CellValueC hanged(ByVal sender As
System.Object, ByVal e As System.Windows. Forms.DataGridV iewCellEventArg s)
Handles DataGridViewDet ails.CellValueC hanged

Dim myNewValue As Integer =
Me.DataGridView Details.Rows(e. RowIndex).Cells (e.ColumnIndex) .Value

Me.DataGridView Details.Rows(e. RowIndex).Cells (e.ColumnIndex) .Value =
myNewValue

End Sub

"Ryan" <Ty****@newsgro ups.nospamwrote in message
news:eT******** ******@TK2MSFTN GP03.phx.gbl...
>I have a DataGridView which displays numeric (Int32) data from an
underlying database. I want the numbers to be displayed in numeric format
"#,###" (with commas). I want to also limit the user so they can only
input numerical values. Is there any way to do this? Currently my
formatting works but if the user enters a value manually the formatting is
not applied to the new value. Also I haven't found a way to allow only
numerical input. Code is below.

So for example if the underlying value is 13200 once the data is read into
the DataGrid it's displayed as 13,200. If I manually change it and type
in 13200 it stays that way, without the comma.

Thanks,
Ryan
Me.DataGridView Details.Columns .Add("Number", "Number")

With Me.DataGridView Details.Columns ("Number")

.DefaultCellSty le.Format = "#,###"

.DefaultCellSty le.Alignment = DataGridViewCon tentAlignment.B ottomRight

End With


Jan 4 '07 #2
Hi Ryan,

I have written a test sample regarding your scenario, however, I found that
once the DataColumn type in the datasource is of type "Integer", the
DataGridView will format the data into "#,###" without any problem. The
full sample code is listed below:

Private Sub Form1_Load(ByVa l sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load
Dim dt As DataTable = New DataTable("test ")
dt.Columns.Add( New DataColumn("col umn1", GetType(Integer )))
dt.Columns.Add( New DataColumn("col umn2", GetType(String) ))

Dim i As Integer
For i = 0 To 5
Dim dr As DataRow
dr = dt.NewRow()
dr("column1") = i * 1000
dr("column2") = "item" + i.ToString()
dt.Rows.Add(dr)
Next

Me.Column1.Data PropertyName = "column1"
Me.Column1.Valu eType = GetType(Integer )
Me.Column1.Defa ultCellStyle.Fo rmat = "#,###"

Me.Column2.Data PropertyName = "column2"
Me.Column1.Valu eType = GetType(String)

Me.DataGridView 1.DataSource = dt
End Sub

Note: Column1 and Column2 are 2 DataGridViewTex tBoxColumn(s) added from
designer.

Based on my test, once the "column1" is of type "Integer", the manually
input integer data in "column1" will be formatted into "#,###" style
without any problem. So, do you use "Integer" type in the datacolumn?

To restrict the user input as numeric data, you have 2 approaches:

#1, Restrict single key input to decimal character. You may get this done
by register the KeyDown event of TextBox in the DataGridViewTex tBoxColumn
and filter non-decimal keys with SuppressKeyPres s property, the sample code
is listed below:

Private Sub DataGridView1_E ditingControlSh owing(ByVal sender As
System.Object, ByVal e As
System.Windows. Forms.DataGridV iewEditingContr olShowingEventA rgs) Handles
DataGridView1.E ditingControlSh owing

If Me.DataGridView 1.CurrentCell.C olumnIndex = 0 And Not e.Control
Is Nothing Then
Dim tb As TextBox = CType(e.Control , TextBox)
AddHandler tb.KeyDown, AddressOf TextBox_KeyDown
End If

End Sub

Private Sub TextBox_KeyDown (ByVal sender As System.Object, ByVal e As
System.Windows. Forms.KeyEventA rgs)
If Keys.D0 < e.KeyData And e.KeyData < Keys.D9 Then
e.Handled = False
Else
e.Handled = True
e.SuppressKeyPr ess = True
End If
End Sub

The sample code handles DataGridView.Ed itingControlSho wing event and get
the TextBox reference through e.Control property. Then it registers the
event for TextBox.

#2, Do not validate the single key press, but delay the validation to the
commit time. You may handle DataGridView.Ce llValidating event and validate
the UI input. If the input is incorrect(based on the Integer.TryPaus e
result), you may set Cancel property to true to cancel the commit:

Private Sub DataGridView1_C ellValidating(B yVal sender As System.Object,
ByVal e As System.Windows. Forms.DataGridV iewCellValidati ngEventArgs)
Handles DataGridView1.C ellValidating
If e.ColumnIndex = 0 And Not e.FormattedValu e = String.Empty Then

Dim i As Integer
Dim str As String = CType(e.Formatt edValue, String)
str = str.Replace("," , String.Empty)
If Not Integer.TryPars e(str, i) Then
MsgBox("Please input integer data")
e.Cancel = True
End If

End If
End Sub

These 2 code snippets both work well on my side. You may choose one of
these 2 solutions based on your application's requirement.

Hope this helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Jan 5 '07 #3
Thanks for the help. I don't want to set the type of the column to Integer
because I have other rows at the bottom of the datagrid that are not Integer
type (Account Codes which contain alphanumeric values). Still thanks for
mentioning this I wasn't aware of how to set the datatype and it could come
in handy for other projects. I considered making the non-integer rows part
of a 2nd datagridview but this doubles the amount of code I have to right
and layout isn't as nice without a lot of code in Resize events. No matter
my current method works fine as long as I can limit the user to only input
digit keys.. so on to part 2 of your code..

I tried your #1 method because I do want to validate on each single key
press (I want non-numeric keys to not even show up). The
EditingControlS howing event only fires when I first enter the cell. This
appears to be what you've intended it to do. However, the other event
TextBox_KeyDown never fires once I'm in edit mode in the cell. Why would
this event never trigger? Any ideas?

Thanks again for your detailed response..

Ryan

""Jeffrey Tan[MSFT]"" <je***@online.m icrosoft.comwro te in message
news:XL******** ********@TK2MSF TNGHUB02.phx.gb l...
Hi Ryan,

I have written a test sample regarding your scenario, however, I found
that
once the DataColumn type in the datasource is of type "Integer", the
DataGridView will format the data into "#,###" without any problem. The
full sample code is listed below:

Private Sub Form1_Load(ByVa l sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load
Dim dt As DataTable = New DataTable("test ")
dt.Columns.Add( New DataColumn("col umn1", GetType(Integer )))
dt.Columns.Add( New DataColumn("col umn2", GetType(String) ))

Dim i As Integer
For i = 0 To 5
Dim dr As DataRow
dr = dt.NewRow()
dr("column1") = i * 1000
dr("column2") = "item" + i.ToString()
dt.Rows.Add(dr)
Next

Me.Column1.Data PropertyName = "column1"
Me.Column1.Valu eType = GetType(Integer )
Me.Column1.Defa ultCellStyle.Fo rmat = "#,###"

Me.Column2.Data PropertyName = "column2"
Me.Column1.Valu eType = GetType(String)

Me.DataGridView 1.DataSource = dt
End Sub

Note: Column1 and Column2 are 2 DataGridViewTex tBoxColumn(s) added from
designer.

Based on my test, once the "column1" is of type "Integer", the manually
input integer data in "column1" will be formatted into "#,###" style
without any problem. So, do you use "Integer" type in the datacolumn?

To restrict the user input as numeric data, you have 2 approaches:

#1, Restrict single key input to decimal character. You may get this done
by register the KeyDown event of TextBox in the DataGridViewTex tBoxColumn
and filter non-decimal keys with SuppressKeyPres s property, the sample
code
is listed below:

Private Sub DataGridView1_E ditingControlSh owing(ByVal sender As
System.Object, ByVal e As
System.Windows. Forms.DataGridV iewEditingContr olShowingEventA rgs) Handles
DataGridView1.E ditingControlSh owing

If Me.DataGridView 1.CurrentCell.C olumnIndex = 0 And Not e.Control
Is Nothing Then
Dim tb As TextBox = CType(e.Control , TextBox)
AddHandler tb.KeyDown, AddressOf TextBox_KeyDown
End If

End Sub

Private Sub TextBox_KeyDown (ByVal sender As System.Object, ByVal e As
System.Windows. Forms.KeyEventA rgs)
If Keys.D0 < e.KeyData And e.KeyData < Keys.D9 Then
e.Handled = False
Else
e.Handled = True
e.SuppressKeyPr ess = True
End If
End Sub

The sample code handles DataGridView.Ed itingControlSho wing event and get
the TextBox reference through e.Control property. Then it registers the
event for TextBox.

#2, Do not validate the single key press, but delay the validation to the
commit time. You may handle DataGridView.Ce llValidating event and validate
the UI input. If the input is incorrect(based on the Integer.TryPaus e
result), you may set Cancel property to true to cancel the commit:

Private Sub DataGridView1_C ellValidating(B yVal sender As System.Object,
ByVal e As System.Windows. Forms.DataGridV iewCellValidati ngEventArgs)
Handles DataGridView1.C ellValidating
If e.ColumnIndex = 0 And Not e.FormattedValu e = String.Empty Then

Dim i As Integer
Dim str As String = CType(e.Formatt edValue, String)
str = str.Replace("," , String.Empty)
If Not Integer.TryPars e(str, i) Then
MsgBox("Please input integer data")
e.Cancel = True
End If

End If
End Sub

These 2 code snippets both work well on my side. You may choose one of
these 2 solutions based on your application's requirement.

Hope this helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no
rights.

Jan 5 '07 #4
Ok, I got it working, just had to modify a few things in the code. Instead
of using a TextBox control I used a DataGridViewTex tBoxEditingCont rol. Also
changed it so it excepts the number pad as well.

Ryan

If Not e.Control Is Nothing Then

Dim tb As DataGridViewTex tBoxEditingCont rol = CType(e.Control ,
DataGridViewTex tBoxEditingCont rol)

AddHandler tb.KeyDown, AddressOf TextBox_KeyDown

End If

Private Sub TextBox_KeyDown (ByVal sender As System.Object, ByVal e As
System.Windows. Forms.KeyEventA rgs)

If (Keys.D0 <= e.KeyData And e.KeyData <= Keys.D9) Or (Keys.NumPad0 <=
e.KeyData And e.KeyData <= Keys.NumPad9) Then

e.Handled = False

Else

e.Handled = True

e.SuppressKeyPr ess = True

End If

End Sub

"Ryan" <Ty****@newsgro ups.nospamwrote in message
news:%2******** ********@TK2MSF TNGP03.phx.gbl. ..
Thanks for the help. I don't want to set the type of the column to
Integer because I have other rows at the bottom of the datagrid that are
not Integer type (Account Codes which contain alphanumeric values). Still
thanks for mentioning this I wasn't aware of how to set the datatype and
it could come in handy for other projects. I considered making the
non-integer rows part of a 2nd datagridview but this doubles the amount of
code I have to right and layout isn't as nice without a lot of code in
Resize events. No matter my current method works fine as long as I can
limit the user to only input digit keys.. so on to part 2 of your code..

I tried your #1 method because I do want to validate on each single key
press (I want non-numeric keys to not even show up). The
EditingControlS howing event only fires when I first enter the cell. This
appears to be what you've intended it to do. However, the other event
TextBox_KeyDown never fires once I'm in edit mode in the cell. Why would
this event never trigger? Any ideas?

Thanks again for your detailed response..

Ryan

""Jeffrey Tan[MSFT]"" <je***@online.m icrosoft.comwro te in message
news:XL******** ********@TK2MSF TNGHUB02.phx.gb l...
>Hi Ryan,

I have written a test sample regarding your scenario, however, I found
that
once the DataColumn type in the datasource is of type "Integer", the
DataGridView will format the data into "#,###" without any problem. The
full sample code is listed below:

Private Sub Form1_Load(ByVa l sender As System.Object, ByVal e As
System.EventAr gs) Handles MyBase.Load
Dim dt As DataTable = New DataTable("test ")
dt.Columns.Add( New DataColumn("col umn1", GetType(Integer )))
dt.Columns.Add( New DataColumn("col umn2", GetType(String) ))

Dim i As Integer
For i = 0 To 5
Dim dr As DataRow
dr = dt.NewRow()
dr("column1") = i * 1000
dr("column2") = "item" + i.ToString()
dt.Rows.Add(dr)
Next

Me.Column1.Data PropertyName = "column1"
Me.Column1.Valu eType = GetType(Integer )
Me.Column1.Defa ultCellStyle.Fo rmat = "#,###"

Me.Column2.Data PropertyName = "column2"
Me.Column1.Valu eType = GetType(String)

Me.DataGridView 1.DataSource = dt
End Sub

Note: Column1 and Column2 are 2 DataGridViewTex tBoxColumn(s) added from
designer.

Based on my test, once the "column1" is of type "Integer", the manually
input integer data in "column1" will be formatted into "#,###" style
without any problem. So, do you use "Integer" type in the datacolumn?

To restrict the user input as numeric data, you have 2 approaches:

#1, Restrict single key input to decimal character. You may get this done
by register the KeyDown event of TextBox in the DataGridViewTex tBoxColumn
and filter non-decimal keys with SuppressKeyPres s property, the sample
code
is listed below:

Private Sub DataGridView1_E ditingControlSh owing(ByVal sender As
System.Objec t, ByVal e As
System.Windows .Forms.DataGrid ViewEditingCont rolShowingEvent Args) Handles
DataGridView1. EditingControlS howing

If Me.DataGridView 1.CurrentCell.C olumnIndex = 0 And Not e.Control
Is Nothing Then
Dim tb As TextBox = CType(e.Control , TextBox)
AddHandler tb.KeyDown, AddressOf TextBox_KeyDown
End If

End Sub

Private Sub TextBox_KeyDown (ByVal sender As System.Object, ByVal e As
System.Windows .Forms.KeyEvent Args)
If Keys.D0 < e.KeyData And e.KeyData < Keys.D9 Then
e.Handled = False
Else
e.Handled = True
e.SuppressKeyPr ess = True
End If
End Sub

The sample code handles DataGridView.Ed itingControlSho wing event and get
the TextBox reference through e.Control property. Then it registers the
event for TextBox.

#2, Do not validate the single key press, but delay the validation to the
commit time. You may handle DataGridView.Ce llValidating event and
validate
the UI input. If the input is incorrect(based on the Integer.TryPaus e
result), you may set Cancel property to true to cancel the commit:

Private Sub DataGridView1_C ellValidating(B yVal sender As
System.Objec t,
ByVal e As System.Windows. Forms.DataGridV iewCellValidati ngEventArgs)
Handles DataGridView1.C ellValidating
If e.ColumnIndex = 0 And Not e.FormattedValu e = String.Empty Then

Dim i As Integer
Dim str As String = CType(e.Formatt edValue, String)
str = str.Replace("," , String.Empty)
If Not Integer.TryPars e(str, i) Then
MsgBox("Please input integer data")
e.Cancel = True
End If

End If
End Sub

These 2 code snippets both work well on my side. You may choose one of
these 2 solutions based on your application's requirement.

Hope this helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
============== =============== =============== ======
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent
issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each
follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
============== =============== =============== ======
This posting is provided "AS IS" with no warranties, and confers no
rights.


Jan 5 '07 #5
Turns out I spoke too soon. This event handles all cells in the column so
now it limits my input into other cells in the column that I want to allow
users to input alphanumeric data.

"Ryan" <Ty****@newsgro ups.nospamwrote in message
news:%2******** *******@TK2MSFT NGP06.phx.gbl.. .
Ok, I got it working, just had to modify a few things in the code.
Instead of using a TextBox control I used a
DataGridViewTex tBoxEditingCont rol. Also changed it so it excepts the
number pad as well.

Ryan

If Not e.Control Is Nothing Then

Dim tb As DataGridViewTex tBoxEditingCont rol = CType(e.Control ,
DataGridViewTex tBoxEditingCont rol)

AddHandler tb.KeyDown, AddressOf TextBox_KeyDown

End If

Private Sub TextBox_KeyDown (ByVal sender As System.Object, ByVal e As
System.Windows. Forms.KeyEventA rgs)

If (Keys.D0 <= e.KeyData And e.KeyData <= Keys.D9) Or (Keys.NumPad0 <=
e.KeyData And e.KeyData <= Keys.NumPad9) Then

e.Handled = False

Else

e.Handled = True

e.SuppressKeyPr ess = True

End If

End Sub

"Ryan" <Ty****@newsgro ups.nospamwrote in message
news:%2******** ********@TK2MSF TNGP03.phx.gbl. ..
>Thanks for the help. I don't want to set the type of the column to
Integer because I have other rows at the bottom of the datagrid that are
not Integer type (Account Codes which contain alphanumeric values).
Still thanks for mentioning this I wasn't aware of how to set the
datatype and it could come in handy for other projects. I considered
making the non-integer rows part of a 2nd datagridview but this doubles
the amount of code I have to right and layout isn't as nice without a lot
of code in Resize events. No matter my current method works fine as long
as I can limit the user to only input digit keys.. so on to part 2 of
your code..

I tried your #1 method because I do want to validate on each single key
press (I want non-numeric keys to not even show up). The
EditingControl Showing event only fires when I first enter the cell. This
appears to be what you've intended it to do. However, the other event
TextBox_KeyDow n never fires once I'm in edit mode in the cell. Why would
this event never trigger? Any ideas?

Thanks again for your detailed response..

Ryan

""Jeffrey Tan[MSFT]"" <je***@online.m icrosoft.comwro te in message
news:XL******* *********@TK2MS FTNGHUB02.phx.g bl...
>>Hi Ryan,

I have written a test sample regarding your scenario, however, I found
that
once the DataColumn type in the datasource is of type "Integer", the
DataGridVie w will format the data into "#,###" without any problem. The
full sample code is listed below:

Private Sub Form1_Load(ByVa l sender As System.Object, ByVal e As
System.EventA rgs) Handles MyBase.Load
Dim dt As DataTable = New DataTable("test ")
dt.Columns.Add( New DataColumn("col umn1", GetType(Integer )))
dt.Columns.Add( New DataColumn("col umn2", GetType(String) ))

Dim i As Integer
For i = 0 To 5
Dim dr As DataRow
dr = dt.NewRow()
dr("column1") = i * 1000
dr("column2") = "item" + i.ToString()
dt.Rows.Add(dr)
Next

Me.Column1.Data PropertyName = "column1"
Me.Column1.Valu eType = GetType(Integer )
Me.Column1.Defa ultCellStyle.Fo rmat = "#,###"

Me.Column2.Data PropertyName = "column2"
Me.Column1.Valu eType = GetType(String)

Me.DataGridView 1.DataSource = dt
End Sub

Note: Column1 and Column2 are 2 DataGridViewTex tBoxColumn(s) added from
designer.

Based on my test, once the "column1" is of type "Integer", the manually
input integer data in "column1" will be formatted into "#,###" style
without any problem. So, do you use "Integer" type in the datacolumn?

To restrict the user input as numeric data, you have 2 approaches:

#1, Restrict single key input to decimal character. You may get this
done
by register the KeyDown event of TextBox in the
DataGridViewT extBoxColumn
and filter non-decimal keys with SuppressKeyPres s property, the sample
code
is listed below:

Private Sub DataGridView1_E ditingControlSh owing(ByVal sender As
System.Object , ByVal e As
System.Window s.Forms.DataGri dViewEditingCon trolShowingEven tArgs) Handles
DataGridView1 .EditingControl Showing

If Me.DataGridView 1.CurrentCell.C olumnIndex = 0 And Not e.Control
Is Nothing Then
Dim tb As TextBox = CType(e.Control , TextBox)
AddHandler tb.KeyDown, AddressOf TextBox_KeyDown
End If

End Sub

Private Sub TextBox_KeyDown (ByVal sender As System.Object, ByVal e As
System.Window s.Forms.KeyEven tArgs)
If Keys.D0 < e.KeyData And e.KeyData < Keys.D9 Then
e.Handled = False
Else
e.Handled = True
e.SuppressKeyPr ess = True
End If
End Sub

The sample code handles DataGridView.Ed itingControlSho wing event and get
the TextBox reference through e.Control property. Then it registers the
event for TextBox.

#2, Do not validate the single key press, but delay the validation to
the
commit time. You may handle DataGridView.Ce llValidating event and
validate
the UI input. If the input is incorrect(based on the Integer.TryPaus e
result), you may set Cancel property to true to cancel the commit:

Private Sub DataGridView1_C ellValidating(B yVal sender As
System.Object ,
ByVal e As System.Windows. Forms.DataGridV iewCellValidati ngEventArgs)
Handles DataGridView1.C ellValidating
If e.ColumnIndex = 0 And Not e.FormattedValu e = String.Empty Then

Dim i As Integer
Dim str As String = CType(e.Formatt edValue, String)
str = str.Replace("," , String.Empty)
If Not Integer.TryPars e(str, i) Then
MsgBox("Please input integer data")
e.Cancel = True
End If

End If
End Sub

These 2 code snippets both work well on my side. You may choose one of
these 2 solutions based on your application's requirement.

Hope this helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
============= =============== =============== =======
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent
issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each
follow
up response may take approximately 2 business days as the support
professiona l working with you may need further investigation to reach
the
most efficient resolution. The offering is not appropriate for
situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are
best
handled working with a dedicated Microsoft Support Engineer by
contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
============= =============== =============== =======
This posting is provided "AS IS" with no warranties, and confers no
rights.



Jan 5 '07 #6
Bah sorry about all the posting. I just moved the condition to check the
current cell to my KeyDown handler so it only limits keys if they're in the
right cell. Easy fix.

"Ryan" <Ty****@newsgro ups.nospamwrote in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
Turns out I spoke too soon. This event handles all cells in the column so
now it limits my input into other cells in the column that I want to allow
users to input alphanumeric data.

"Ryan" <Ty****@newsgro ups.nospamwrote in message
news:%2******** *******@TK2MSFT NGP06.phx.gbl.. .
>Ok, I got it working, just had to modify a few things in the code.
Instead of using a TextBox control I used a
DataGridViewTe xtBoxEditingCon trol. Also changed it so it excepts the
number pad as well.

Ryan

If Not e.Control Is Nothing Then

Dim tb As DataGridViewTex tBoxEditingCont rol = CType(e.Control ,
DataGridViewTe xtBoxEditingCon trol)

AddHandler tb.KeyDown, AddressOf TextBox_KeyDown

End If

Private Sub TextBox_KeyDown (ByVal sender As System.Object, ByVal e As
System.Windows .Forms.KeyEvent Args)

If (Keys.D0 <= e.KeyData And e.KeyData <= Keys.D9) Or (Keys.NumPad0 <=
e.KeyData And e.KeyData <= Keys.NumPad9) Then

e.Handled = False

Else

e.Handled = True

e.SuppressKeyP ress = True

End If

End Sub

"Ryan" <Ty****@newsgro ups.nospamwrote in message
news:%2******* *********@TK2MS FTNGP03.phx.gbl ...
>>Thanks for the help. I don't want to set the type of the column to
Integer because I have other rows at the bottom of the datagrid that are
not Integer type (Account Codes which contain alphanumeric values).
Still thanks for mentioning this I wasn't aware of how to set the
datatype and it could come in handy for other projects. I considered
making the non-integer rows part of a 2nd datagridview but this doubles
the amount of code I have to right and layout isn't as nice without a
lot of code in Resize events. No matter my current method works fine as
long as I can limit the user to only input digit keys.. so on to part 2
of your code..

I tried your #1 method because I do want to validate on each single key
press (I want non-numeric keys to not even show up). The
EditingContro lShowing event only fires when I first enter the cell.
This appears to be what you've intended it to do. However, the other
event TextBox_KeyDown never fires once I'm in edit mode in the cell.
Why would this event never trigger? Any ideas?

Thanks again for your detailed response..

Ryan

""Jeffrey Tan[MSFT]"" <je***@online.m icrosoft.comwro te in message
news:XL****** **********@TK2M SFTNGHUB02.phx. gbl...
Hi Ryan,

I have written a test sample regarding your scenario, however, I found
that
once the DataColumn type in the datasource is of type "Integer", the
DataGridVi ew will format the data into "#,###" without any problem. The
full sample code is listed below:

Private Sub Form1_Load(ByVa l sender As System.Object, ByVal e As
System.Event Args) Handles MyBase.Load
Dim dt As DataTable = New DataTable("test ")
dt.Columns.Add( New DataColumn("col umn1", GetType(Integer )))
dt.Columns.Add( New DataColumn("col umn2", GetType(String) ))

Dim i As Integer
For i = 0 To 5
Dim dr As DataRow
dr = dt.NewRow()
dr("column1") = i * 1000
dr("column2") = "item" + i.ToString()
dt.Rows.Add(dr)
Next

Me.Column1.Data PropertyName = "column1"
Me.Column1.Valu eType = GetType(Integer )
Me.Column1.Defa ultCellStyle.Fo rmat = "#,###"

Me.Column2.Data PropertyName = "column2"
Me.Column1.Valu eType = GetType(String)

Me.DataGridView 1.DataSource = dt
End Sub

Note: Column1 and Column2 are 2 DataGridViewTex tBoxColumn(s) added from
designer.

Based on my test, once the "column1" is of type "Integer", the manually
input integer data in "column1" will be formatted into "#,###" style
without any problem. So, do you use "Integer" type in the datacolumn?

To restrict the user input as numeric data, you have 2 approaches:

#1, Restrict single key input to decimal character. You may get this
done
by register the KeyDown event of TextBox in the
DataGridView TextBoxColumn
and filter non-decimal keys with SuppressKeyPres s property, the sample
code
is listed below:

Private Sub DataGridView1_E ditingControlSh owing(ByVal sender As
System.Objec t, ByVal e As
System.Windo ws.Forms.DataGr idViewEditingCo ntrolShowingEve ntArgs)
Handles
DataGridView 1.EditingContro lShowing

If Me.DataGridView 1.CurrentCell.C olumnIndex = 0 And Not
e.Control
Is Nothing Then
Dim tb As TextBox = CType(e.Control , TextBox)
AddHandler tb.KeyDown, AddressOf TextBox_KeyDown
End If

End Sub

Private Sub TextBox_KeyDown (ByVal sender As System.Object, ByVal e
As
System.Windo ws.Forms.KeyEve ntArgs)
If Keys.D0 < e.KeyData And e.KeyData < Keys.D9 Then
e.Handled = False
Else
e.Handled = True
e.SuppressKeyPr ess = True
End If
End Sub

The sample code handles DataGridView.Ed itingControlSho wing event and
get
the TextBox reference through e.Control property. Then it registers the
event for TextBox.

#2, Do not validate the single key press, but delay the validation to
the
commit time. You may handle DataGridView.Ce llValidating event and
validate
the UI input. If the input is incorrect(based on the Integer.TryPaus e
result), you may set Cancel property to true to cancel the commit:

Private Sub DataGridView1_C ellValidating(B yVal sender As
System.Objec t,
ByVal e As System.Windows. Forms.DataGridV iewCellValidati ngEventArgs)
Handles DataGridView1.C ellValidating
If e.ColumnIndex = 0 And Not e.FormattedValu e = String.Empty
Then

Dim i As Integer
Dim str As String = CType(e.Formatt edValue, String)
str = str.Replace("," , String.Empty)
If Not Integer.TryPars e(str, i) Then
MsgBox("Please input integer data")
e.Cancel = True
End If

End If
End Sub

These 2 code snippets both work well on my side. You may choose one of
these 2 solutions based on your application's requirement.

Hope this helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
============ =============== =============== ========
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent
issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each
follow
up response may take approximately 2 business days as the support
profession al working with you may need further investigation to reach
the
most efficient resolution. The offering is not appropriate for
situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are
best
handled working with a dedicated Microsoft Support Engineer by
contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
============ =============== =============== ========
This posting is provided "AS IS" with no warranties, and confers no
rights.



Jan 5 '07 #7
Hi Ryan,

Glad to see you have figured out all the obstacles!

Yes, I was also strange to find that
DataGridViewEdi tingControlShow ingEventArgs class did not provide a property
to tell the column index. Further research found that we should get the
current editing cell index from the DataGridView.Cu rrentCell.Colum nIndex
property, so I provided it in the first reply.

Ok, if you need further help, please feel free to post, thanks

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Jan 8 '07 #8

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

Similar topics

0
1351
by: milk-jam | last post by:
How do i use the first raw of my datagridview for filtering the data in the datagridview ?
10
13339
by: milk-jam | last post by:
I'm trying to set my datagridview so that the first row will be left blank and to use it as a filtering filed for the datagridview. Until now I was using 2 datagridview the upper one with a header that sort and one row for filtering and the lower one with no header for the data. Only it is very complicated to work this way cause for example...
6
13530
by: Satya | last post by:
Hi, I am using a DataGridView to display a large amount of data and so need to use filters for displaying certain data. For this I want to provide a textbox for each column of the DataGridView so that the user can type in any text and use that text as the filter. I would like to have this textbox row as the first row of the DataGridView just...
3
32255
by: Rich | last post by:
Hello, I am populating a datagridview from a datatable and filtering the number of rows with a dataview object. Is there a way to retrieve the rows displayed by the datagridview into a separate datatable without having to loop through each column in the datagridview? Or is there a way to retrieve the rows from the original datatable...
5
21367
by: bob | last post by:
Now this ought to be a simple matter. But nothing's simple in the Net world, I'm finding. In vb6 you could use "!" to force text to upper case in the format function. I've searched the vb.net help system and can't find any help on formatting text. There's plenty of help formatting numbers, dates, and times, though. I'm in the phase of...
1
2397
by: Rich | last post by:
Hello, I need to change the font size of a datagridview to accommodate a screen resolution of 800x600. I know how to set the fontsize at runtime datagridview1.Font = New Font("arial", 8, FontStyle.Regular) But I would prefer to set this at the property sheet. The datasource for the datagridview is a dataview that I use for filtering.
4
19793
by: NvrBst | last post by:
I have a log viewer. I sort the DataGridView by the Time Column and then run a function to set all cell backcolors depending if the cell above is different. This works correctly, however, when I resort a column (by clicking any of the column headers) then all the colors revert back to the origional white background. Is there a way to...
1
3432
by: AJG | last post by:
Hi there. I am using a library called SOCI that has a method to set a stream which it uses to log SQL queries. The signature is as follows: void setLogStream(std::ostream *s); This works great when used with something like setLogStream(&std::cerr). However, I would like to add more context to the query logged. Specifically, I'd like to...
1
5119
by: Ben456 | last post by:
Hello, I'm trying to figure out how to keep my cell formatting the same even after I've clicked a column sort header. Basically I've programmatically changed forecolors and backcolors of several different cells in my datagridview. When I the click the sort header it resorts the data but all my color formatting is lost. Is there a way...
0
7789
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...
0
8144
Oralloy
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. ...
0
8301
jinu1996
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...
0
6551
agi2029
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...
1
5670
isladogs
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...
0
5361
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3803
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1400
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1132
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.