0

I have a datagridview on a windows form in vb.net. In one or more columns I want the text to be limited to numbers, including negative signs and one decimal point. I have the column property "format" set to 3 digit numbers, but I can still enter any text I want. So what is the trick to get VB to use the property?

I used this with no change in the behavior. https://msdn.microsoft.com/en-us/library/f9x2790s(v=vs.110).aspx

I also tried this with no change in the behavior.

DataGridView1.Columns(2).DefaultCellStyle.Format = "N3"

from here: How to format numbers to 3 decimal place in datagridview using vb.net

Community
  • 1
  • 1
CreoGuy
  • 37
  • 1
  • 1
  • 6
  • So do you want characters to be restricted in these columns while typing, or do you want validation to check to see if the edited cells are valid? – Sturgus Apr 13 '17 at 18:14
  • The top two answers to [this question](http://stackoverflow.com/q/12645458/832052) should help. – djv Apr 13 '17 at 18:19
  • The underlying datatype of the columns datasource will do that for you – Ňɏssa Pøngjǣrdenlarp Apr 13 '17 at 18:28
  • this is an unbound datagridview in vb.net The link is for C++ I think. I don't care the method. Why is there a property for this when VB ignores the property? How can I populate the cells with numbers that are not considered strings when the data source is unbound? I'm loading the data from a textfile. – CreoGuy Apr 13 '17 at 18:32

2 Answers2

0

I found this and it works. But how can I limit the number to 3 decimal places?

Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
        If Not IsNumeric(DataGridView1(3, e.RowIndex).Value) Then
            DataGridView1(3, e.RowIndex).Value = ""
        End If
End Sub
CreoGuy
  • 37
  • 1
  • 1
  • 6
0

If we're building off of what you have, and you just want to change it to 3 decimal places, try the following:

Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
    If Not IsNumeric(DataGridView1(3, e.RowIndex).Value) Then
        DataGridView1(3, e.RowIndex).Value = ""
    Else
        DataGridView1(3, e.RowIndex).Value = Decimal.Parse(DataGridView1(3, e.RowIndex).Value).ToString("N3")
    End If
End Sub

Please note that this answer will round the third decimal place if a fourth exists.

Sturgus
  • 666
  • 4
  • 18