我有一个从SQL Server 2008数据库中的存储过程读取的GridView控件,我试图更改行的背景颜色是某个单元格包含某些文本。无论出于何种原因,我提出的解决方案只有在GridView中有多行时才有效。如果GridView中只有一行,则该行的行颜色不会更改。如果需要,我会发布更多代码,但我正在使用OnRowDataBound
GridView控件的事件。
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等于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");
}
}
答案 0 :(得分:2)
首先 - 您不需要循环遍历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如果您在标签中有文字,请检查标签的文字,而不是使用此标签
Label lbl = (Label)e.Row.FindControl("myTextLabel");
if (lbl.Text == "C6N") {
e.Row.BackColor = System.Drawing.Color.Red;
}