2017-10-12 38 views
1

我在ASPX新的,我有一個這樣的網格:使用驗證與綁定列

<asp:GridView ID="grdViewTareas" AutoGenerateColumns="false" runat="server" CssClass="Grid"> 
    <Columns> 
    <asp:BoundField DataField="stardate" HeaderText="Fecha Inicio" DataFormatString="{0:d}" ItemStyle-HorizontalAlign="Center" /> 
    <asp:BoundField DataField="duedate" HeaderText="Fecha Fin" DataFormatString="{0:d}" ItemStyle-HorizontalAlign="Center" /> 
    <asp:BoundField DataField="progress" HeaderText="% de Avance" ItemStyle-HorizontalAlign="Center" /> 
    </Columns> 
</asp:GridView> 

我要爲網格中的每一行畫柱的背景,例如做了驗證:

if (progress < 100){ 
background-color: red; 
} 

我該如何做到這一點。問候

回答

1

您使用OnRowDataBound事件。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    //check if the row is a datarow 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     //cast the row back to a datarowview 
     DataRowView row = e.Row.DataItem as DataRowView; 

     DateTime _currentDate = new DateTime(); 
     DateTime _dueDate = new DateTime(); 

     //first, check if the date fields are null or empty and then try to convert 
     if (!string.IsNullOrEmpty(row["currentDate"].ToString())) 
     { 
      _currentDate = Convert.ToDateTime(row["currentDate"]); 
     } 

     if (!string.IsNullOrEmpty(row["dueDate"].ToString())) 
     { 
      _dueDate = Convert.ToDateTime(row["dueDate"]); 
     } 

     //check the value of progress and set the background color 
     if (Convert.ToInt32(row["progress"]) < 100 && _currentDate > _dueDate) 
     { 
      e.Row.Cells[0].BackColor = Color.Red; 
     } 
    } 
} 

您需要將OnRowDataBound="GridView1_RowDataBound"添加到GridView。

如果您綁定的List<Myclass>你做這個類的列表:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    //check if the row is a datarow 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     //if you bound a list of classes to the GridView, cast back to the orignal class 
     MyClass item = e.Row.DataItem as MyClass; 

     //check the propertyu value of the class and set the background color 
     if (item.progress < 100 && item.currentDate > item.dueDate) 
     { 
      e.Row.Cells[0].BackColor = Color.Red; 
     } 
    } 
} 
+0

,如果我想添加'和'有條件的話就用想如果'(Convert.ToInt32(行[「進步」]) <100 && row [「stardate」]> row [「duedate」])'或者我錯了? – Pepe

+0

是的,但你需要轉換爲DateTime'Convert.ToDateTime(row [「duedate」])' – VDWWD

+0

你能檢查我的編輯你的答案嗎?如果我只是使用「進度」驗證它的工作原理:'if(progress <100)',但如果我添加Date驗證像'(progress <100 && currentDate> dueDate)'它會拋出錯誤 – Pepe