[英]Row Data Bound in ASP.NET Grid View C#
我有一個網格視圖,需要綁定 IsActive 字段。但是從數據庫中它是 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";
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.