Change ASP.Net GridView Cell Background color based on condition using C# and VB.Net

Last Reply 3 months ago By pandeyism

Posted 3 months ago

Greetings experts,

The code below checks to see if the filename on the server matches the filename from the database.

If yes, the Listen link is activated, allowing the user to play and listen to recording.

If no file on the server matches the file on the DB for a particular record, the Listen link is disabled.

All of this works great.

The only issue I am not able to resolve is how to add a background color of red to the Listen link if it is disabled.

Any ideas if this is possible?

Many thanks in advance

'/Markup

      <asp:HyperLink runat="server" id="HyperLink1"
      NavigateUrl='<%#String.Format("http://is-server1/Archives/{1}/snoop_{0}.wav", Eval("filename"), Eval("servers")) %>'
      Enabled='<%# RecordingExists(Eval("filename", "{0}"), Eval("servers", "{0}")) %>' ToolTip='<%# If(RecordingExists(Eval("filename", "{0}"), Eval("servers", "{0}")), "Play recording", "No audio found") %>' Text="Listen"/>


'/VB
    Protected Function RecordingExists(ByVal filename As String, ByVal servername As String) As Boolean
        Dim virtualPath As String = String.Format("/Archives/{1}/snoop_{0}.wav", filename, servername)
        Dim physicalPath As String = Server.MapPath(virtualPath)
        Return System.IO.File.Exists(physicalPath)
    End Function

 

Posted 3 months ago

Hi simflex,

Refer below link and sample.

Change Background color of GridView Row using RowDataBound event in ASP.Net using C# and VB.Net

HTML

<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" 
    onrowdatabound="gvCustomers_RowDataBound">
    <Columns>
        <asp:BoundField DataField="CustomerId" HeaderText="Id" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:HyperLink runat="server" NavigateUrl="~/CS.aspx" ID="HyperLink1" Text="Listen" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Namespaces

C#

using System.Data;
using System.Drawing;

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[] { new DataColumn("CustomerId", typeof(int)), new DataColumn("Name", typeof(string)) });
        dt.Rows.Add(1, "Mudassar Khan");
        dt.Rows.Add(2, "John Hammod");
        dt.Rows.Add(3, "Rober");
        dt.Rows.Add(1, "Suzzain");
        this.gvCustomers.DataSource = dt;
        this.gvCustomers.DataBind();
    }
}

protected void gvCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[0].Text == "1")
        {
            e.Row.Cells[2].BackColor = Color.Red;
        }
    }
}

Screenshot