简体   繁体   中英

How to convert a specific datagridview column values to double in c#?

I am new to c# and I am using windows forms.

Anyone knows how can I convert specific datagridview column values to double using dataGridView1_CellValidating (or using other events) in C#? Please help. Thank you

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    // for example I want to Validate column4 values if it is not a double then convert it to double.
}

This is How you can Set a Double Value in datagridcell

double value = double.Parse(dataGridView1.Rows[2].Cells[3].Value.ToString());
dataGridView1.Rows[2].Cells[3].Value = value.ToString("N2");

ToString("N2") will format the double value with two Decimal places

 private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        //Write in the array massive numbers from сolumn numOfcolumn
        int numOfcolumn = 3; //for example
        if (numOfcolumn > this.dataGridView1.ColumnCount) numOfcolumn = this.dataGridView1.ColumnCount;
        double[] massive = new double[this.dataGridView1.RowCount];
        for (int i = 0; i < this.dataGridView1.RowCount; i++)
        massive[i] = this.dataGridView1.Rows[i].Cells[numOfcolumn].Value != null ? Convert.ToDouble(this.dataGridView1.Rows[i].Cells[numOfcolumn].Value.ToString()) : 0.0;
    }

You can set up the formatting when you initialize your column and avoid any events.

If you are using the designer simply set the Format property of the column to N2 . To get to a columns Format property you must highlight your grid. Then open your columns collection window and select the column you want to change.

在此处输入图片说明

Under the Appearance category you will need to click the DefaultCellStyle property and then set the Format property to N2 .

在此处输入图片说明

If you are creating the columns dynamically then set this property after initializing the column:

var dgTextBoxCol = new DataGridViewTextBoxColumn();
dgTextBoxCol.Name = "yourColumnName";
dgTextBoxCol.DefaultCellStyle.Format = "N2";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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