gridview标签颜色变化

时间:2014-10-15 17:01:02

标签: c# asp.net .net gridview

 protected void getmessagelisting()
    {    
          ds = new DataSet();
            SQL = "Select * from [magaj].[message] where UId='" + Session["UserID"].ToString() + "'  order by ID desc";
            SqlDataAdapter da = new SqlDataAdapter(SQL, _connect());
            da.Fill(ds, "message");
            Grid_Joblist.DataSource = ds;
            Grid_Joblist.Columns[0].Visible = true;
            Grid_Joblist.DataBind();
            Grid_Joblist.Columns[0].Visible = false;
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                if (ds.Tables[0].Rows[i]["isread"].ToString() == "0")
                {
                    //  (e.Row.FindControl("lblsubject") as Label).ForeColor = Color.Yellow;
                    foreach (GridViewRow row in Grid_Joblist.Rows)
                    {
                        Label lblsubject = row.FindControl("lblsubject") as Label;
                        lblsubject.ForeColor = Color.Yellow;

                    }
                }
            }
}

现在当我运行它时,我将以适当的方式绑定所有数据 但是当我想做任何有value of isread=0的数据时,我想改变那个标签的颜色。

但当任何1行满足此if条件时,它也会改变所有其他标签颜色..

我想只更改标签颜色(如果它满足isread=0),而对于其他不满足的数据那么它将是不同的颜色

我该怎么做?

2 个答案:

答案 0 :(得分:3)

你可以做一件事:

只需在标签中打印您的isread值,如:

<asp:Label runat="server" ID="lblisread" Text='<%#Eval("isread")%>' Visible="false"/>

然后按以下方式更改您的功能:

   foreach (GridViewRow row in Grid_Joblist.Rows)
    {
        Label lblsubject = row.FindControl("lblsubject") as Label;
        Label lblisread = row.FindControl("lblisread ") as Label;

        if (lblisread..Text == "0")
        {
            lblsubject.ForeColor = Color.Red;

        }
        else
        {
            lblsubject.ForeColor = Color.Yellow;
        }

    }

并完成了...... !! 干杯.. !!!

答案 1 :(得分:0)

使用GridView RowDataBound事件来使用set label color。

如下所示

void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
  {

    if(e.Row.RowType == DataControlRowType.DataRow)
    {
      // Display the company name in italics.
      System.Data.DataRow row = (System.Data.DataRow)e.Row.DataItem;
      if(row["isread"].ToString()=="0")
        {

           Control l = e.Row.FindControl("lblsubject");
  ((Label)l).ForeColor= System.Drawing.Color.Yellow;

    }

  }

未经过测试的代码。

请查看以下链接以获取更多信息:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound%28v=vs.110%29.aspx

Row background color in gridview?