ASP.NET 网格视图 C# 中绑定的行数据
Row Data Bound in ASP.NET Grid View C#
我有一个网格视图,需要从数据库绑定 IsActive field.But,它是 1 或 0。
错误显示System.InvalidCastException: 'Specified cast is not valid.'
网格
<asp:BoundField DataField="IsActive" HeaderText="Status">
<ItemStyle Width="200px" />
</asp:BoundField>
代码
protected void grid1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (((int)DataBinder.Eval(e.Row.DataItem, "IsActive") == 1))
{
e.Row.Cells[12].Text = "Active";
}
else
{
e.Row.Cells[12].Text = "Inactive";
}
}
}
尝试先抓取基础数据项,然后检查它。
protected void grid1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView rowView = null;
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Retrieve the underlying data item
rowView = (DataRowView)e.Row.DataItem;
// Make sure we can parse and compare what we get.
if (int.TryParse(rowView["IsActive"].ToString(), out int isActive) && isActive == 1)
{
e.Row.Cells[12].Text = "Active";
}
else
{
e.Row.Cells[12].Text = "Inactive";
}
}
}
我有一个网格视图,需要从数据库绑定 IsActive field.But,它是 1 或 0。
错误显示System.InvalidCastException: 'Specified cast is not valid.'
网格
<asp:BoundField DataField="IsActive" HeaderText="Status">
<ItemStyle Width="200px" />
</asp:BoundField>
代码
protected void grid1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (((int)DataBinder.Eval(e.Row.DataItem, "IsActive") == 1))
{
e.Row.Cells[12].Text = "Active";
}
else
{
e.Row.Cells[12].Text = "Inactive";
}
}
}
尝试先抓取基础数据项,然后检查它。
protected void grid1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView rowView = null;
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Retrieve the underlying data item
rowView = (DataRowView)e.Row.DataItem;
// Make sure we can parse and compare what we get.
if (int.TryParse(rowView["IsActive"].ToString(), out int isActive) && isActive == 1)
{
e.Row.Cells[12].Text = "Active";
}
else
{
e.Row.Cells[12].Text = "Inactive";
}
}
}