简体   繁体   English

vb.net-datagridview-格式不起作用

[英]vb.net - datagridview - Formatting is not working

The situation : 情况

I have a datagridview with one column (col1). 我有一列(col1)的datagridview。

In the datagrid definition (design view), i have created this row, and set the formatting to C2 (or C0, or C - I tried them all). 在数据网格定义(设计视图)中,我创建了这一行,并将格式设置为C2(或C0或C-我尝试了所有方法)。

then, I load my datagrid view programmatically : 然后,我以编程方式加载我的datagrid视图:

dbl_myValue as double   
dbl_myValue = 6.99

datagridview1.item(0,0) = dbl_myValue

The datagridView shows the data correcly : 6.99$ datagridView正确显示数据:6.99 $

When I "spy" on the datagridview.item(0,0), the "Value" property is a Double. 当我在datagridview.item(0,0)上“间谍”时, “值”属性是Double。

the problem : 问题 :

It doesn't work if the user manually enter a value : click in the cell, enter a numeric value (let's say 100, without decimal to avoid complexity) and then leave the cell (so no more in edit mode). 如果用户手动输入一个值,则不起作用 :单击该单元格,输入一个数值(例如100,不带小数,以避免复杂性),然后离开该单元格(因此不再处于编辑模式)。 The formating just dont applies. 格式只是不适用。

When I "spy" on the datagridview.item(0,0), the "value" property is a STRING. 当我在datagridview.item(0,0)上“间谍”时, “值”属性为STRING。

So I guess this is the problem, but what can I do? 所以我想这是问题所在,但是我该怎么办?

I've tried to go in CellValidating and stuffing it with code like: 我试图进入CellValidating并用如下代码填充它:

Private Sub DataGridView1_CellValidating(....) 

Dim c As Control = DataGridView_WorkOrderAddition.EditingControl

c.text = formatNumeric(c.text) 

c.text = convert.toDouble(c.text)

But it still doesn't work. 但这仍然行不通。

Yes, when the DGV is not bound then cells default to storing strings. 是的,当未绑定DGV时,单元格默认为存储字符串。 Setting the column's CellType property can solve that, Decimal is most appropriate for handling money values. 设置列的CellType属性可以解决以下问题:Decimal最适合处理货币值。 You'll also need to implement the DataError event so you can warn the user that the string cannot be converted. 您还需要实现DataError事件,以便可以警告用户该字符串无法转换。 Thus: 从而:

Public Class Form1
    Public Sub New()
        InitializeComponent()
        DataGridView1.Columns(0).ValueType = GetType(Decimal)
    End Sub

    Private Sub DataGridView1_DataError(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles DataGridView1.DataError
        MessageBox.Show(e.Exception.Message)
    End Sub
End Class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM