1

I am using a GridView in asp.net.

The first column is a list of button controls -

<ItemTemplate>
  <asp:Button ID="statusButton" runat="server" Text="Select" 
            OnClick="statusButton_CheckedChanged" />
</ItemTemplate>

However I want to modify the background color and Text values of this button on data bind based on the value of another column in the table.

My problem being I need to check the values of the other column as they are retrieved, they will either be 1 or -1 and that value will set the design of the button.

How can I check the values of this bound field -

<asp:BoundField DataField="EXCLUDE" HeaderText="EXCLUDE" SortExpression="EXCLUDE" 
     ReadOnly="True" HeaderStyle-CssClass = "hideGridColumn" 
     ItemStyle-CssClass="hideGridColumn"/>

To then set the colour and text of the button?

2 Answers 2

1

You can use the RowDataBound event of the gridview, for example:

    myGrid.RowDataBound += new GridViewRowEventHandler(myGrid_RowDataBound);
    void myGrid_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                //Raised after each row is databound
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    string value = e.Row.Cells[5].Text; //sixth column
                    if (value == "1")
                    {
                        //change button color (assuming button is in first column)
                        Button myButton = e.Row.Cells[0].Controls[0] as Button;
                        myButton.BackColor = Color.Red;
Sign up to request clarification or add additional context in comments.

2 Comments

This can retrieve the values! However the button gets this error -Cannot implicitly convert type 'System.Web.UI.Control' to 'System.Web.UI.WebControls.Button'. An explicit conversion exists are you missing a cast? How can I resolve this?
@Jambo: try e.Row.Cells[0].Controls[0] as Button; I updated my answer as well
1

Change it as follows

<ItemTemplate>
     <asp:Button ID="statusButton" runat="server" Text="Select" 
        OnClick="statusButton_CheckedChanged" />
</ItemTemplate>

use different css-classes according to your condition

.class1{
 color:red;
 font-size:10;
}
.class2{
 color:blue;
 font-size:12;
}

<ItemTemplate>
     <asp:Button ID="statusButton" runat="server" Text="Select" 
        CssClass='<%# Convert.ToString(Eval("EXCLUDE"))== "1" ? "class1" : "class2" %>' 
        OnClick="statusButton_CheckedChanged" />
</ItemTemplate>

You can use it from the C# on RowDataBound event as suggested by @edwin

1 Comment

Good advice with the CSS class however I needed slightly more control over handling the values in the code behind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.