使用c#根据条件在Gridview上更改单元格颜色
本文关键字:单元格 颜色 Gridview 条件 使用 | 更新日期: 2023-09-27 18:02:02
我试图改变单元格的颜色,如果余额小于零,然后使其为红色。我得到这个错误:
Input string was not in a correct format.
这是我的gridview
<asp:GridView ID="gvTest" runat="server" Width="700px" CssClass="table table-hover table-bordered table-responsive" OnRowDataBound = "OnRowDataBound"
AutoGenerateColumns="false" DataKeyNames="ID"
AllowPaging="true"
OnPageIndexChanging="OnPaging_gvBookKeeping"
PageSize="25">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" HtmlEncode="true" />
<asp:BoundField DataField="FullName" HeaderText="Name" HtmlEncode="true" />
<asp:BoundField DataField="Remaining_Ballance" DataFormatString="{0:C0}" HeaderText="Remaining Ballance" HtmlEncode="true" />
<asp:BoundField DataField="Note" HeaderText="Note" HtmlEncode="true" />
<asp:BoundField DataField="fully_paid" HeaderText="Fully Paid" HtmlEncode="true" />
<asp:TemplateField ItemStyle-Width="30px" HeaderText="Edit Link">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" CausesValidation="false" runat="server" Text="Edit" OnClick="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#E5E5E5" />
<PagerSettings Position="TopAndBottom" />
<PagerStyle BackColor="#CCCCCC" ForeColor="#FF3300" HorizontalAlign="Center" />
</asp:GridView>
下面是
后面的代码protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TableCell cell = e.Row.Cells[2];
int ballance = int.Parse(cell.Text);
if (ballance < 0)
{
cell.BackColor = Color.Red;
}
}
}
它在这行失败
int ballance = int.Parse(cell.Text);
balance列的数据类型是decimal(10,2)
看起来应该是TableCell cell = e.Row.Cells[2];
而不是TableCell cell = e.Row.Cells[3];
列索引从0开始,而不是1。
在您的示例中,这意味着您正在尝试将Notes
字段的值解析为Int
。
编辑
您可能还会发现DataFormatString="{0:C0}"
使用货币符号(例如$/£)格式化数字,并且该字符不能转换为整数。
按照建议添加断点将帮助您识别此问题。
您还可以在int周围使用Try {} catch{}块。解析语句,使错误转换不会破坏您的代码。
这并不意味着单元格会正确格式化,只是它不会破裂。
也可以使用int。TryParse方法,这通常是更好的解决方案。TryParse肯定更快。这有点令人困惑,所以这里有一个例子
// See if we can parse the 'text' string.
// If we can't, TryParse will return false.
// Note the "out" keyword in TryParse.
string text1 = "x";
int num1;
bool res = int.TryParse(text1, out num1);
if (res == false)
{
// String is not a number.
}
// Use int.TryParse on a valid numeric string.
string text2 = "10000";
int num2;
if (int.TryParse(text2, out num2))
{
// It was assigned.
}
尝试将代码更改为
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
dynamic dataItem = e.Row.DataItem;
if(dataItem != null && dataItem.Remaining_Ballance < 0)
{
e.Row.Cells[2].BackColor = Color.Red;
}
}
}
注意:我使用动态数据类型的dataItem,因为我不知道你的实际对象类型。您应该使用实际的数据类型,并且还需要进行强制转换。