2013-05-28 140 views
0

我有一個從SQL Server 2008數據庫中的存儲過程讀取的GridView控件,我試圖更改某行的背景顏色是某個單元格包含某些文本。無論出於何種原因,我所提出的解決方案僅適用於GridView中存在多行的情況。如果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 

的目的是改變在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"); 
      } 

     } 
+0

你有沒有測試,以確保'OnRowDataBound'事件被解僱? –

+0

@MikePrecup只學習C#/ asp.net,我會如何測試? – wootscootinboogie

+0

@MikePrecup我將一個斷點放入並調試,並且它們的事件從未激發過。 – wootscootinboogie

回答

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 - 因爲這會返回除文本以外的所有其他方式。

例如,如果你在一個標籤中的文本,然後檢查標籤的文本,而不是通過使用這個代替

Label lbl = (Label)e.Row.FindControl("myTextLabel");

if (lbl.Text == "C6N") { 
    e.Row.BackColor = System.Drawing.Color.Red; 
} 
+0

非常感謝您的支持,我不知道GridView中每一行都會調用這個方法。這看起來是我所需要的。 Mil gracias :) – wootscootinboogie

相關問題