简体   繁体   中英

Change text color in 1 cell in gridview

I have a gridview with this column:

<asp:TemplateField HeaderText="Importe" SortExpression="importe">
<EditItemTemplate>
    <asp:Label ID="lblImporte" runat="server" Text='<%# Eval("importe") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
    <asp:Label ID="lblImporte" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "importe", "{0:#,##0.00}") %>'></asp:Label>
</ItemTemplate>
<ItemStyle ForeColor="Red" />

By default, the text color is red. Comparing programmatically two amounts I need to change the Font color.

In my code I have

Label lblImporte = (Label)gvTablaMes.Rows[e.RowIndex].FindControl("lblImporte");

I tried with this without success.

lblImporte.ForeColor = System.Drawing.Color.Green;

I think that I have to use something like that, but I dont know how to use the index for the column (I wrote an X)

gvTablaMes.Rows[e.RowIndex].Cells[X].ForeColor = System.Drawing.Color.Green;

You have traversed the gridview in normal mode. But the label control you need to find is inside the edittemplate.
For that include the following Rowdatabound event in the codebehind file.

protected void gvTablaMes_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if ((e.Row.RowState == DataControlRowState.Edit) || (e.Row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate)))
        {
            // the above checking is to verify whether the rows as well as alternating rows are in edit mode
            Label lblImporte = (Label)e.Row.FindControl("lblImporte");
            lblImporte.ForeColor = System.Drawing.Color.Green;
        }
    }

And dont forget to include the OnRowDataBound="gvTablaMes_RowDataBound" to the gridview tag.
Hope this helps.Let me know of any issues in this.
Happy coding :)

try changing in page_load() method for example,

protected void Page_Load(object sender, EventArgs e)
{

    Label1.ForeColor = System.Drawing.Color.Orange;

}

<form id="form1" runat="server">
<div>

    <asp:Label ID="Label1" runat="server"></asp:Label>

</div>
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM