Set Display format for winform DataGridView

二次信任 提交于 2019-12-24 04:40:24

问题


I am new to WinForms development, currently I am maintaining an application developed in .Net 2.0

In the application, I have grid with column called Length which displays the value with unit. I have used CellFormatting event to format the cell value, otherwise it is just number.

But when user start editing I wouldn't want unit to be displayed, user should be allowed enter only numbers.

Is there any straight forward way to do it? Events or Properties to be set on the grid?


回答1:


You should set the unit in the event DataGridView_CellFormatting

void DataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 1)
    {
        int value;
        if(e.Value != null && int.TryParse(e.Value.ToString(), out value))
        {
            e.Value = value.ToString("#mm");
        }
    }
}



回答2:


You should handle the EditingControlShowing event to change the current cell format.

    private void dataGridView1_EditingControlShowing(object sender, 
                               DataGridViewEditingControlShowingEventArgs e)
    {
        if (dataGridView1.CurrentCell.ColumnIndex == 1)
        {
            e.CellStyle.Format = "#";
            e.Control.Text = dataGridView1.CurrentCell.Value.ToString();
        }
    } 



回答3:


You can Set you Format String using CellStyle Builder an set the Custom format to # mm

How to do it :

  1. Right click on Grid, then Properties
  2. In the property window, click the button that will popup up the Edit Columns Dialog
  3. Select the cell you want to format
  4. On the right side of the Edit Columns Dialog select the DefaultCellStyle property
  5. Click the DefaultCellStyle property, then the CellStyleBuilder dialog will open
  6. Here you have the format property, this will give you the Format String Dialog
  7. Set the Custom property to #mm you will see the preview at the bottom
  8. Click OK ... till you are back to your Grid...


来源:https://stackoverflow.com/questions/11340292/set-display-format-for-winform-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!