Datagridview Cell Formatting Issues

Joined
May 25, 2012
Messages
2
Reaction score
0
Hi,
I am working on a vb6 to vb.net migration project.
I have a datagridview.
My requirement is to show the $ sign,if the user entered numeric data in a cell and if the user presses the "-" key, the - sign should come infront of the data (like -$34) and if again user presses "-" key it should remove the - sign (like $34).

I have managed to do this in a round about way.like,I am changing a global variable value to TRUE if user presses "-" key (using the keycode). and in the cell leave event,if this variable is true and cell value does not have any "-" sign then concatinating "-" sign with the cell value.

This method is not correct and there should be a proper and easy method. I am searching for that. Any help appreciated in this regard.
Thanks,
Sumith
 
Joined
May 25, 2012
Messages
2
Reaction score
0
I got it.
First, need to format the column as currency

Code:
[FONT=Courier New]DataGridView1.Columns("C"[/FONT]).DefaultCellStyle.Format = "c"

1DataGridView1.Columns("C").DefaultCellStyle.Format = "c"



Next, add eventhandler for cells

Code:
Private Sub dataGridView1_EditingControlShowing(ByVal sender As Object, _ByVal e As DataGridViewEditingControlShowingEventArgs) _
Handles DataGridView1.EditingControlShowing
Dim txtEdit As TextBox = e.Control

RemoveHandler txtEdit.KeyPress, AddressOf txtEdit_Keypress
AddHandler txtEdit.KeyPress, AddressOf txtEdit_Keypress
end sub


1Private Sub dataGridView1_EditingControlShowing(ByVal sender As Object, _
2ByVal e As DataGridViewEditingControlShowingEventArgs) _
3Handles DataGridView1.EditingControlShowing
4Dim txtEdit As TextBox = e.Control
5
6RemoveHandler txtEdit.KeyPress, AddressOf txtEdit_Keypress
7AddHandler txtEdit.KeyPress, AddressOf txtEdit_Keypress



And, in txtedit_keypress,

Code:
Private Sub txtEdit_Keypress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
 If e.KeyChar = "-" Then
                Dim curCell As DataGridViewCell = DataGridView1.CurrentCell
                If curCell.ColumnIndex = 2 Then
                    curCell.Value = -CDec(curCell.Value)
                    DataGridView1.RefreshEdit()
                    e.Handled = True
                End If
            End If
end sub
01Private Sub txtEdit_Keypress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
02If e.KeyChar = "-" Then
03Dim curCell As DataGridViewCell = DataGridView1.CurrentCell
04If curCell.ColumnIndex = 2 Then
05curCell.Value = -CDec(curCell.Value)
06DataGridView1.RefreshEdit()
07e.Handled = True
08End If
09End If
10end sub



This will work as desired.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top