Kate
Kate

Reputation: 945

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.
}

Upvotes: 0

Views: 7816

Answers (3)

jaredbaszler
jaredbaszler

Reputation: 4809

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.

enter image description here

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

enter image description here

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";

Upvotes: 1

Babkin
Babkin

Reputation: 21

 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;
    }

Upvotes: 2

Jamshaid K.
Jamshaid K.

Reputation: 4547

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

Upvotes: 1

Related Questions