我有一个GridView控件,从SQL Server 2008数据库中的存储过程中读取,我试图改变一行的背景颜色是某个单元格包含某些文本。无论出于何种原因,我提出的解决方案只有在GridView中有不止一行时才有效。如果GridView中只有一行,那么该行的行颜色不会改变。如果需要,我会发布更多的代码,但我使用的是OnRowDataBound
事件。
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
目的是改变GridView的行颜色,如果column1Desc等于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");
}
}
第一件事-你不需要循环遍历你的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
-因为这将返回除文本之外的所有内容。
E。G如果标签中有文本,则通过使用this
来检查标签的文本。 Label lbl = (Label)e.Row.FindControl("myTextLabel");
if (lbl.Text == "C6N") {
e.Row.BackColor = System.Drawing.Color.Red;
}