Get int value from cell in GridView for inventory control?

2.3k views Asked by At

Basically I can't get the value from cells, the column contains only integers and using Convert gives exceptions so is adding fila.Cells[4].Value, been trying some solutiosn I've found online (commented in the code), but still.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    foreach (GridViewRow fila in Tabla.Rows)
    {
        //int celda = Convert.ToInt32(Tabla.Rows[4].ToString()); //ArgumentOutOfRangeException
        //var celda = Convert.ToInt32(fila.Cells[4].ToString()); //FormatException
        //var celda = Convert.ToInt32(fila.Cells[4]); //InvalidCastException
        if (celda > 10)
        {
            //Visual Alert on cell
        }
    }
}

Inside the if statement, it should display an alert (out of stock, low stock, etc)

Is it even possible to do that or I'm just wasting my time?

2

There are 2 answers

0
Alex Hodge On

For the RowDataBound event you really want to use the event GridViewRowEventArgs to get the current row. You can do something like this.

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (Convert.toInt32(e.Row.Cells[4].Text) > 10)
            {
                //alert
            }
        }
0
VDWWD On

You could run into problems if you use e.Row.Cells[i].Text to check the cell data. If you format a cell like this <%# string.Format("{0:c}", 35000) %>, converting it back to integer 35000 will give the Input string was not in a correct format error because it has been formatted to a string as € 35.000,00. The same goes for DateTime values.

A better approach is to convert the GridViewRowEventArgs back to the original format and do comparison on that.

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //if the bound data is a generic list, cast back to an individual listitem
            Book book = e.Row.DataItem as Book;
            if (book.id > 3)
            {
                //add an attribute to the row
                e.Row.Attributes.Add("style", "background-color: red");
                //or hide the entire row
                e.Row.Visible = false;
            }

            //if the bound data is a datatable or sql source, cast back as datarowview
            DataRowView row = e.Row.DataItem as DataRowView;
            if (Convert.ToInt32(row["id"]) > 4)
            {
                //add an attribute to a cell in the row
                e.Row.Cells[1].Attributes.Add("style", "background-color: red");
                //or replace the contents of the cell
                e.Row.Cells[1].Text = "SOLD OUT";
            }
        }
    }