2012-11-26 85 views
2

我在ASP.Net - C#中有一個Gridview。我有一列名爲AssignmentExam。在那一欄中,我有任務或考試的名稱,例如:"Exam 1","Assignment 5"我希望每個作業都是紅色,考試應該是藍色的。根據數據更改gridview中一行的顏色

在SQL Server或我的代碼中執行它的最佳方法是什麼?如果是這樣的代碼是什麼?

回答

0

首先在變量中查找行索引。在下面的代碼中,我使用了index作爲變量。

grdWithLocation.Rows[index].BackColor = Color.FromArgb(255, 238, 238, 238); 
2

您可以通過單獨設置BackColor財產的每一行設置在GridView行的背景色。要根據行中的數據完成此操作,您需要檢查該行是否已被綁定,您可以在RowDataBound事件中執行此操作。下面是標記爲一個基本的GridView的快速一點,我們掛接到服務器端事件:

<asp:GridView runat="server" AutoGenerateColumns="False" OnRowDataBound="TestGridView_RowDataBound" ID="TestGridView"> 
    <Columns> 
     <asp:BoundField DataField="Type" HeaderText="Assignment/Exam" /> 
     <asp:BoundField DataField="Name" HeaderText="Name" /> 
    </Columns> 
</asp:GridView> 

protected void Page_Load(object sender, EventArgs e) 
{ 
    DataTable tests = new DataTable(); 
    tests.Columns.Add(new DataColumn("Type")); 
    tests.Columns.Add(new DataColumn("Name")); 
    tests.AcceptChanges(); 

    tests.Rows.Add(new []{"Assignment","StackOverflow Basics"}); 
    tests.Rows.Add(new[]{"Exam","Expert Markdown"}); 
    tests.Rows.Add(new[]{"Exam","Upvoting"}); 
    tests.Rows.Add(new[]{"Assignment","Rep Changes"}); 

    TestGridView.DataSource = tests; 
    TestGridView.DataBind(); 
} 

在事件的代碼,我們可以得到我們正在綁定到單獨的數據行的保持並檢查值,這樣我們就可以相應地設置背景色:

protected void TestGridView_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    // Ignore the first row which is the header 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     // Get hold of the row and then the DataRow that it's being bound to 
     GridViewRow row = e.Row; 
     DataRow data = ((DataRowView)row.DataItem).Row; 

     // Look at the value and set the colour accordingly 
     switch (data.Field<string>("Type")) 
     { 
      case "Assignment": 
       row.BackColor = System.Drawing.Color.FromName("Blue"); 
       break; 
      case "Exam": 
       row.BackColor = System.Drawing.Color.FromName("Red"); 
       break; 
     } 
    } 
} 

這工作正常,雖然你可能要考慮也將文本顏色設置爲白色,這是稍微容易閱讀。

但是,您可能希望未來獲得更多的靈活性,例如,如果添加名爲「Lab」的第三種評估類型爲綠色,則需要更改/重新編譯/重新測試/重新部署代碼。相反,如果你通過從數據庫中指定的顏色,然後再使用,在RowDataBound事件,您可以避免一些工作,例如:

protected void TestGridView_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    // Ignore the first row which is the header 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     // Get hold of the row and then the DataRow that it's being bound to 
     GridViewRow row = e.Row; 
     DataRow data = ((DataRowView)row.DataItem).Row; 

     row.BackColor = System.Drawing.Color.FromName(data.Field<string>("BackColour"); 
     row.ForeColor = System.Drawing.Color.FromName(data.Field<string>("TextColour"); 
    } 
} 
+0

的問題是,我不知道該行的名稱,在「作業或考試」列中,無論何時「分配」,該行都是紅色的......我如何說如果該列下的單元格是分配的...... –

+0

@PedramRaffi您在您的領域有什麼源數據?它只是一個名字,例如作業1,考試3? – PhilPursglove