基本上我不能从单元格中获得值,列中只包含整数,使用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
语句中,它应该显示一个警报(缺货,低库存等)
这可能吗?还是我只是在浪费时间?
对于RowDataBound事件,您实际上希望使用事件GridViewRowEventArgs来获取当前行。你可以这样做。
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (Convert.toInt32(e.Row.Cells[4].Text) > 10)
{
//alert
}
}
如果使用e.Row.Cells[i].Text
检查单元格数据,可能会遇到问题。如果将单元格格式化为<%# string.Format("{0:c}", 35000) %>
,将其转换回整数35000将会给出Input string was not in a correct format
错误,因为它已被格式化为字符串€ 35.000,00
。DateTime
值也一样。
一个更好的方法是将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";
}
}
}