我有一個從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");
}
}
你有沒有測試,以確保'OnRowDataBound'事件被解僱? –
@MikePrecup只學習C#/ asp.net,我會如何測試? – wootscootinboogie
@MikePrecup我將一個斷點放入並調試,並且它們的事件從未激發過。 – wootscootinboogie