[英]Formatting programmatically changing the row color of a GridView control
我有一个GridView控件,从SQL Server 2008数据库中的存储过程读取,我试图更改行的背景颜色是某个单元格包含某些文本。 无论出于何种原因,我提出的解决方案只有在GridView中有多行时才有效。 如果GridView中只有一行,则该行的行颜色不会更改。 如果需要,我会发布更多代码,但我正在使用GridView控件的OnRowDataBound
事件。
用于OnRowDataBound
事件的c#
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//in every row I would like to check the text of the second cell
if (GridView1.Rows[i].Cells[1].Text == "C6N")
{
e.Row.BackColor = System.Drawing.Color.Red;
}
}
}
这是GridView控件的结构
columnName1 column1Desc columnName2 column2Desc
one C6N two zzz
目的是在column1Desc等于C6N
更改GridView的行颜色
下面是绑定GridView的按钮单击。 在if(rdr.HasRows)
下面if(rdr.HasRows)
我写入了响应对象并且它实际上打印了正确的C6N值,但是当结果集只有一行时,格式化更改不会发生。
protected void Button2_Click(object sender, EventArgs e)
{
//craete the drugString variable
string drugString = string.Join(string.Empty,druglist.ToArray()).TrimEnd(',');
//create the connection string
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
//create the connection object
using (SqlConnection con = new SqlConnection(cs))
{
//create the command object
using (SqlCommand cmd = new SqlCommand("spMakeTempTable2", con))
{
//don't forget to open the connection
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@drugList", drugString);
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
if (rdr.HasRows)
Response.Write(GridView1.Rows[0].Cells[1].Text);
//this line prints to the screen as it should
else
Response.Write("There were no drug combinations present");
}
}
第一件事 - 您不需要循环遍历gridview行,因为无论如何都会使用每行调用此方法。
您已经知道要查询的行,因为它只调用此方法并通过GridViewRowEventArgs
属性传递信息。
所以这样的事情可能更适合:
GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
// you only want to check DataRow type, and not headers, footers etc.
if (e.Row.RowType == DataControlRowType.DataRow) {
// you already know you're looking at this row, so check your cell text
if (e.Row.Cells(1).Text == "C6N") {
e.Row.BackColor = System.Drawing.Color.Red;
}
}
}
另外 - 您是否使用模板来存放您正在检查的文本? 因为如果你是,你需要获得文本所在的控件 - 而不仅仅是Cell(1).Text
- 因为这将返回除文本之外的所有其他方式。
EG如果您在标签中有文本,请检查标签的文本,而不是使用此标签
Label lbl = (Label)e.Row.FindControl("myTextLabel");
if (lbl.Text == "C6N") {
e.Row.BackColor = System.Drawing.Color.Red;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.