从GridView中的单元格获取int值以进行库存控制?

时间:2016-11-02 00:13:28

标签: c# asp.net gridview cell databound

基本上我无法从单元格中获取值,该列仅包含整数,并且使用Convert提供异常,因此添加fila.Cells[4].Value,尝试了一些我在网上找到的解决方案(在代码),但仍然。

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

if声明中,它应显示警告(缺货,库存不足等)

甚至可以这样做,还是我只是在浪费时间?

2 个答案:

答案 0 :(得分:4)

对于RowDataBound事件,您确实希望使用事件GridViewRowEventArgs来获取当前行。你可以这样做。

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

答案 1 :(得分:0)

如果使用e.Row.Cells[i].Text检查单元格数据,则可能会遇到问题。如果格式化像<%# string.Format("{0:c}", 35000) %>这样的单元格,将其转换回整数35000会产生Input string was not in a correct format错误,因为它已被格式化为字符串€ 35.000,00DateTime值也是如此。

更好的方法是将GridViewRowEventArgs转换回原始格式并对其进行比较。

    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";
            }
        }
    }
相关问题