-
May 22nd, 2017, 04:30 PM
#1
Thread Starter
Lively Member
Formatting in DataGridView not working correctly?
Hello! I am trying to format a specific column to work with currency. I went into the designer, changed the format setting for the column to C2(currency to second decimal place) and when I go to debug, it for some reason does not format. Here is the line of codenames correlate with where they go to column)
Code:
DataGridView1.Rows.Add(txtName.Text, txtCredit.Text, txtPrize.Text, txtPurchaser.Text)
I had made a variable named credits and had it declared as a decimal and had it be credits = txtcredit.text and in that line of code above have it do: credits.ToString("c") and see if that would work. It didn't :/
Thanks in advance!( I am still learning too)
-
May 22nd, 2017, 04:41 PM
#2
Lively Member
Re: Formatting in DataGridView not working correctly?
Hi Dragnorian,
i believe you need this:
Code:
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
'this formats all cells in column 0 excluding the newrow
If e.ColumnIndex = 0 AndAlso e.RowIndex <> DataGridView1.NewRowIndex Then
e.Value = CDec(e.Value).ToString("f2")
e.FormattingApplied = True
End If
End Sub
This was taken from:
http://www.vbforums.com/showthread.p...idview-control
Hope it works!
-
May 22nd, 2017, 05:28 PM
#3
Thread Starter
Lively Member
Re: Formatting in DataGridView not working correctly?
It did! Thank you very much!!!
-
May 22nd, 2017, 08:53 PM
#4
Re: Formatting in DataGridView not working correctly?
The reason that it didn't work in the first place is that numeric format strings only work on numbers and you are providing a String rather than a number. You don't actually need to do as Weeluke suggests if the grid is read-only. You just have to provide a number, e.g.
vb.net Code:
DataGridView1.Rows.Add(txtName.Text, CDec(txtCredit.Text), txtPrize.Text, txtPurchaser.Text)
If the grid is not read-only though, I think it would still fail if and when the user typed a new value into a cell, because that new value would be interpreted as a String. I think that, in that case, you'd have to bind the grid to a data source that defined that column as being numeric, e.g. a DataTable with a DataColumn that had its DataType set to Decimal.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|