Zaid
Zaid

Reputation: 63

retrieving number value from datagridview C#

I am trying to retrieve a numerical value from datagridview. The data type for both the value in the table, and the variable (weeklyTotal), are integer. Also I am trying to cast it into integer. I looked through the whole website for similar problems, and yet none of the solutions were helpful. The error message that I am getting is “when casting form a number, the value must be less than infinity”. I went back to my table more than one time to make sure that I don’t have invalid value.

it's a runtime error and the IDE always point at this line

weeklyTotal += (int)dataGridView1.Rows[i].Cells[1].Value;

for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
        {
            sdate = dataGridView1.Rows[i].Cells[2].Value.ToString();
            ddate = dataGridView1.Rows[i].Cells[3].Value.ToString();

            if ((weekFirstDay <= Convert.ToInt32(sdate) &&
                Convert.ToInt32(sdate) <= (weekFirstDay + 7))||(weekFirstDay <= `Convert.ToInt32(ddate) &&`
                Convert.ToInt32(ddate) <= (weekFirstDay + 7)))
            {
                dataGridView1.Rows[i].Selected = true;
                dataGridView1.Rows[i].Visible = true;
                weeklyTotal += (int)dataGridView1.Rows[i].Cells[1].Value;

                //weeklyTotalString = dataGridView1.Rows[i].Cells[1].Value.ToString();
                //weeklyTotal += Convert.ToInt32(weeklyTotalString);


            }
            else

Upvotes: 6

Views: 23263

Answers (3)

Tarec
Tarec

Reputation: 3255

That's because the following won't cast your cell value to the int type:

(int) dataGridView1.Rows[i].Cells[1].Value

You're just taking the string saying "hey compiler, please treat it as an int type", but it will still be a string type underneath. Use the Convert.ToInt32 method like you did earlier.

weeklyTotal += Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);

Upvotes: 8

Hemraj Patel
Hemraj Patel

Reputation: 51

int num = Convert.ToInt32(dgv.Rows[i].Cells["col_name"].Value);

Upvotes: 1

nanytech
nanytech

Reputation: 398

You may be trying to to an (int) cast on a DBNull value. I'm assuming that you populating the datagridview with data from the database.

Try this:

if(dataGridView1.Rows[i].Cells[1].Value != DBNull.Value)
{
    weeklyTotal += (int)dataGridView1.Rows[i].Cells[1].Value;
}

Upvotes: 0

Related Questions