472,372 Members | 1,457 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,372 software developers and data experts.

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.DataGridViewDetails.Columns.Add("Number", "Number")

With Me.DataGridViewDetails.Columns("Number")

..DefaultCellStyle.Format = "#,###"

..DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomRight

End With
Jan 4 '07 #1
7 15903
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_CellValueChanged 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 DataGridViewDetails_CellValueChanged(ByVal sender As
System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
Handles DataGridViewDetails.CellValueChanged

Dim myNewValue As Integer =
Me.DataGridViewDetails.Rows(e.RowIndex).Cells(e.Co lumnIndex).Value

Me.DataGridViewDetails.Rows(e.RowIndex).Cells(e.Co lumnIndex).Value =
myNewValue

End Sub

"Ryan" <Ty****@newsgroups.nospamwrote in message
news:eT**************@TK2MSFTNGP03.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.DataGridViewDetails.Columns.Add("Number", "Number")

With Me.DataGridViewDetails.Columns("Number")

.DefaultCellStyle.Format = "#,###"

.DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomRight

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(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim dt As DataTable = New DataTable("test")
dt.Columns.Add(New DataColumn("column1", GetType(Integer)))
dt.Columns.Add(New DataColumn("column2", 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.DataPropertyName = "column1"
Me.Column1.ValueType = GetType(Integer)
Me.Column1.DefaultCellStyle.Format = "#,###"

Me.Column2.DataPropertyName = "column2"
Me.Column1.ValueType = GetType(String)

Me.DataGridView1.DataSource = dt
End Sub

Note: Column1 and Column2 are 2 DataGridViewTextBoxColumn(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 DataGridViewTextBoxColumn
and filter non-decimal keys with SuppressKeyPress property, the sample code
is listed below:

Private Sub DataGridView1_EditingControlShowing(ByVal sender As
System.Object, ByVal e As
System.Windows.Forms.DataGridViewEditingControlSho wingEventArgs) Handles
DataGridView1.EditingControlShowing

If Me.DataGridView1.CurrentCell.ColumnIndex = 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.KeyEventArgs)
If Keys.D0 < e.KeyData And e.KeyData < Keys.D9 Then
e.Handled = False
Else
e.Handled = True
e.SuppressKeyPress = True
End If
End Sub

The sample code handles DataGridView.EditingControlShowing 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.CellValidating event and validate
the UI input. If the input is incorrect(based on the Integer.TryPause
result), you may set Cancel property to true to cancel the commit:

Private Sub DataGridView1_CellValidating(ByVal sender As System.Object,
ByVal e As System.Windows.Forms.DataGridViewCellValidatingEve ntArgs)
Handles DataGridView1.CellValidating
If e.ColumnIndex = 0 And Not e.FormattedValue = String.Empty Then

Dim i As Integer
Dim str As String = CType(e.FormattedValue, String)
str = str.Replace(",", String.Empty)
If Not Integer.TryParse(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
EditingControlShowing 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.microsoft.comwrote in message
news:XL****************@TK2MSFTNGHUB02.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
DataGridView will format the data into "#,###" without any problem. The
full sample code is listed below:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim dt As DataTable = New DataTable("test")
dt.Columns.Add(New DataColumn("column1", GetType(Integer)))
dt.Columns.Add(New DataColumn("column2", 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.DataPropertyName = "column1"
Me.Column1.ValueType = GetType(Integer)
Me.Column1.DefaultCellStyle.Format = "#,###"

Me.Column2.DataPropertyName = "column2"
Me.Column1.ValueType = GetType(String)

Me.DataGridView1.DataSource = dt
End Sub

Note: Column1 and Column2 are 2 DataGridViewTextBoxColumn(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 DataGridViewTextBoxColumn
and filter non-decimal keys with SuppressKeyPress property, the sample
code
is listed below:

Private Sub DataGridView1_EditingControlShowing(ByVal sender As
System.Object, ByVal e As
System.Windows.Forms.DataGridViewEditingControlSho wingEventArgs) Handles
DataGridView1.EditingControlShowing

If Me.DataGridView1.CurrentCell.ColumnIndex = 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.KeyEventArgs)
If Keys.D0 < e.KeyData And e.KeyData < Keys.D9 Then
e.Handled = False
Else
e.Handled = True
e.SuppressKeyPress = True
End If
End Sub

The sample code handles DataGridView.EditingControlShowing 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.CellValidating event and validate
the UI input. If the input is incorrect(based on the Integer.TryPause
result), you may set Cancel property to true to cancel the commit:

Private Sub DataGridView1_CellValidating(ByVal sender As System.Object,
ByVal e As System.Windows.Forms.DataGridViewCellValidatingEve ntArgs)
Handles DataGridView1.CellValidating
If e.ColumnIndex = 0 And Not e.FormattedValue = String.Empty Then

Dim i As Integer
Dim str As String = CType(e.FormattedValue, String)
str = str.Replace(",", String.Empty)
If Not Integer.TryParse(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 DataGridViewTextBoxEditingControl. Also
changed it so it excepts the number pad as well.

Ryan

If Not e.Control Is Nothing Then

Dim tb As DataGridViewTextBoxEditingControl = CType(e.Control,
DataGridViewTextBoxEditingControl)

AddHandler tb.KeyDown, AddressOf TextBox_KeyDown

End If

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

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.SuppressKeyPress = True

End If

End Sub

"Ryan" <Ty****@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP03.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
EditingControlShowing 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.microsoft.comwrote in message
news:XL****************@TK2MSFTNGHUB02.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
DataGridView will format the data into "#,###" without any problem. The
full sample code is listed below:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim dt As DataTable = New DataTable("test")
dt.Columns.Add(New DataColumn("column1", GetType(Integer)))
dt.Columns.Add(New DataColumn("column2", 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.DataPropertyName = "column1"
Me.Column1.ValueType = GetType(Integer)
Me.Column1.DefaultCellStyle.Format = "#,###"

Me.Column2.DataPropertyName = "column2"
Me.Column1.ValueType = GetType(String)

Me.DataGridView1.DataSource = dt
End Sub

Note: Column1 and Column2 are 2 DataGridViewTextBoxColumn(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 DataGridViewTextBoxColumn
and filter non-decimal keys with SuppressKeyPress property, the sample
code
is listed below:

Private Sub DataGridView1_EditingControlShowing(ByVal sender As
System.Object, ByVal e As
System.Windows.Forms.DataGridViewEditingControlSh owingEventArgs) Handles
DataGridView1.EditingControlShowing

If Me.DataGridView1.CurrentCell.ColumnIndex = 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.KeyEventArgs)
If Keys.D0 < e.KeyData And e.KeyData < Keys.D9 Then
e.Handled = False
Else
e.Handled = True
e.SuppressKeyPress = True
End If
End Sub

The sample code handles DataGridView.EditingControlShowing 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.CellValidating event and
validate
the UI input. If the input is incorrect(based on the Integer.TryPause
result), you may set Cancel property to true to cancel the commit:

Private Sub DataGridView1_CellValidating(ByVal sender As
System.Object,
ByVal e As System.Windows.Forms.DataGridViewCellValidatingEve ntArgs)
Handles DataGridView1.CellValidating
If e.ColumnIndex = 0 And Not e.FormattedValue = String.Empty Then

Dim i As Integer
Dim str As String = CType(e.FormattedValue, String)
str = str.Replace(",", String.Empty)
If Not Integer.TryParse(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****@newsgroups.nospamwrote in message
news:%2***************@TK2MSFTNGP06.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
DataGridViewTextBoxEditingControl. Also changed it so it excepts the
number pad as well.

Ryan

If Not e.Control Is Nothing Then

Dim tb As DataGridViewTextBoxEditingControl = CType(e.Control,
DataGridViewTextBoxEditingControl)

AddHandler tb.KeyDown, AddressOf TextBox_KeyDown

End If

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

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.SuppressKeyPress = True

End If

End Sub

"Ryan" <Ty****@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP03.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
EditingControlShowing 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.microsoft.comwrote in message
news:XL****************@TK2MSFTNGHUB02.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
DataGridView will format the data into "#,###" without any problem. The
full sample code is listed below:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim dt As DataTable = New DataTable("test")
dt.Columns.Add(New DataColumn("column1", GetType(Integer)))
dt.Columns.Add(New DataColumn("column2", 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.DataPropertyName = "column1"
Me.Column1.ValueType = GetType(Integer)
Me.Column1.DefaultCellStyle.Format = "#,###"

Me.Column2.DataPropertyName = "column2"
Me.Column1.ValueType = GetType(String)

Me.DataGridView1.DataSource = dt
End Sub

Note: Column1 and Column2 are 2 DataGridViewTextBoxColumn(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
DataGridViewTextBoxColumn
and filter non-decimal keys with SuppressKeyPress property, the sample
code
is listed below:

Private Sub DataGridView1_EditingControlShowing(ByVal sender As
System.Object, ByVal e As
System.Windows.Forms.DataGridViewEditingControlS howingEventArgs) Handles
DataGridView1.EditingControlShowing

If Me.DataGridView1.CurrentCell.ColumnIndex = 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.KeyEventArgs)
If Keys.D0 < e.KeyData And e.KeyData < Keys.D9 Then
e.Handled = False
Else
e.Handled = True
e.SuppressKeyPress = True
End If
End Sub

The sample code handles DataGridView.EditingControlShowing 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.CellValidating event and
validate
the UI input. If the input is incorrect(based on the Integer.TryPause
result), you may set Cancel property to true to cancel the commit:

Private Sub DataGridView1_CellValidating(ByVal sender As
System.Object,
ByVal e As System.Windows.Forms.DataGridViewCellValidatingEve ntArgs)
Handles DataGridView1.CellValidating
If e.ColumnIndex = 0 And Not e.FormattedValue = String.Empty Then

Dim i As Integer
Dim str As String = CType(e.FormattedValue, String)
str = str.Replace(",", String.Empty)
If Not Integer.TryParse(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 #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****@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP02.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****@newsgroups.nospamwrote in message
news:%2***************@TK2MSFTNGP06.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
DataGridViewTextBoxEditingControl. Also changed it so it excepts the
number pad as well.

Ryan

If Not e.Control Is Nothing Then

Dim tb As DataGridViewTextBoxEditingControl = CType(e.Control,
DataGridViewTextBoxEditingControl)

AddHandler tb.KeyDown, AddressOf TextBox_KeyDown

End If

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

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.SuppressKeyPress = True

End If

End Sub

"Ryan" <Ty****@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP03.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
EditingControlShowing 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.microsoft.comwrote in message
news:XL****************@TK2MSFTNGHUB02.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
DataGridView will format the data into "#,###" without any problem. The
full sample code is listed below:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim dt As DataTable = New DataTable("test")
dt.Columns.Add(New DataColumn("column1", GetType(Integer)))
dt.Columns.Add(New DataColumn("column2", 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.DataPropertyName = "column1"
Me.Column1.ValueType = GetType(Integer)
Me.Column1.DefaultCellStyle.Format = "#,###"

Me.Column2.DataPropertyName = "column2"
Me.Column1.ValueType = GetType(String)

Me.DataGridView1.DataSource = dt
End Sub

Note: Column1 and Column2 are 2 DataGridViewTextBoxColumn(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
DataGridViewTextBoxColumn
and filter non-decimal keys with SuppressKeyPress property, the sample
code
is listed below:

Private Sub DataGridView1_EditingControlShowing(ByVal sender As
System.Object, ByVal e As
System.Windows.Forms.DataGridViewEditingControl ShowingEventArgs)
Handles
DataGridView1.EditingControlShowing

If Me.DataGridView1.CurrentCell.ColumnIndex = 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.KeyEventArgs)
If Keys.D0 < e.KeyData And e.KeyData < Keys.D9 Then
e.Handled = False
Else
e.Handled = True
e.SuppressKeyPress = True
End If
End Sub

The sample code handles DataGridView.EditingControlShowing 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.CellValidating event and
validate
the UI input. If the input is incorrect(based on the Integer.TryPause
result), you may set Cancel property to true to cancel the commit:

Private Sub DataGridView1_CellValidating(ByVal sender As
System.Object,
ByVal e As System.Windows.Forms.DataGridViewCellValidatingEve ntArgs)
Handles DataGridView1.CellValidating
If e.ColumnIndex = 0 And Not e.FormattedValue = String.Empty
Then

Dim i As Integer
Dim str As String = CType(e.FormattedValue, String)
str = str.Replace(",", String.Empty)
If Not Integer.TryParse(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 #7
Hi Ryan,

Glad to see you have figured out all the obstacles!

Yes, I was also strange to find that
DataGridViewEditingControlShowingEventArgs 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.CurrentCell.ColumnIndex
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
by: milk-jam | last post by:
How do i use the first raw of my datagridview for filtering the data in the datagridview ?
10
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...
6
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...
3
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...
5
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...
1
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,...
4
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...
1
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...
1
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...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
2
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...
1
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...
1
by: ezappsrUS | last post by:
Hi, I wonder if someone knows where I am going wrong below. I have a continuous form and two labels where only one would be visible depending on the checkbox being checked or not. Below is the...
0
by: jack2019x | last post by:
hello, Is there code or static lib for hook swapchain present? I wanna hook dxgi swapchain present for dx11 and dx9.
0
DizelArs
by: DizelArs | last post by:
Hi all) Faced with a problem, element.click() event doesn't work in Safari browser. Tried various tricks like emulating touch event through a function: let clickEvent = new Event('click', {...

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.