简体   繁体   中英

C# Convert Double to a string from a DataGridView

On my button click I am getting the following error when the value being replaced is only a number (eg 40 ) and it is being replaced by a string (eg AB123 ).

System.Exception: AB123 is not a valid value for Double. --->

System.FormatException: Input string was not in a correct format.

at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)

Button Click:

    private void button2_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < dataGridView1.RowCount; i++)
        {
            if (!RowIsEmpty(i))
            {
                dataGridView1[3, i].Value = Combo.Text;
            }
        }
    }

I have tried implicitly converting this like so:

dataGridView1[3, i].Value.ToString() = Combo.Text;

But that doesn't work, I have also tried calling it as a string like so:

    private void button2_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < dataGridView1.RowCount; i++)
        {
            if (!RowIsEmpty(i))
            {
                string DGVS = dataGridView1[3, i].Value.ToString();
                DGVS =  Combo.Text;
            }
        }
    }

But that doesn't give an error but doesn't actually do anything.

Data is loaded in from an excel file.

Example

Col1  Col2  Col3
AAA   BBB   40

ComboBox:

ABC123

Ok I guess I found the solution:

double price;
bool isDouble = Double.TryParse(textBox1.Text, out price);
if (isDouble)
{
     Convert.ToDouble(textBox1.Text);
     dataGridView1[0, 0].Value = textBox1.Text;
}
else
{
     dataGridView1[0, 0].Value = textBox1.Text;
}

Basically, first check if the textbox is double or not. If is double, convert to double and add it to DGV. If it's string, just add the string into DGV.

Tests:

TextBox1.Text = AAA; //worked
TextBox1.Text = BBB; //worked
TextBox1.Text = 40; //worked
TextBox1.Text = 40.00; //worked
TextBox1.Text = 42,20; //worked

I resolved this (maybe not the best way but it works) by removing and re adding the column after the load into the datagridview but before the update of the combobox value into the rows.

private void button2_Click(object sender, EventArgs e)
{
    DataGridViewTextBoxColumn Column3New = new DataGridViewTextBoxColumn();
    Column3New.Name = "Column3";
    Column3New.HeaderText = "Column3";
    dataGridView1.Columns.RemoveAt(3);
    dataGridView1.Columns.Insert(3, Column3New);
    for (int i = 0; i < dataGridView1.RowCount; i++)
    {
        if (!RowIsEmpty(i))
        {
            dataGridView1[3, i].Value = Combo.Text;
        }
    }
}

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