我有一个 GridView 控件,它从 SQL Server 2008 数据库中的存储过程中读取数据,我试图更改行的背景颜色是某个单元格包含某些文本。无论出于何种原因,我提出的解决方案仅在 GridView 中有不止一行时才有效。如果 GridView 中只有一行,则该行的行颜色不会更改。如果需要,我会发布更多代码,但我使用的OnRowDataBound
是 GridView 控件的事件。
c#OnRowDataBound
事件
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 等于时更改 GridView 的行颜色C6N
下面是绑定 GridView 的按钮单击。在下面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");
}
}