css - 使用 BoundField 在 GridView 上使用验证

标签 css asp.net if-statement aspxgridview

我是 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;
}

我怎样才能做到这一点。问候

最佳答案

您使用 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。

如果你绑定(bind)了一个类列表 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;
        }
    }
}

关于css - 使用 BoundField 在 GridView 上使用验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46715295/

相关文章:

javascript - 如何使用视口(viewport)在垂直中心制作引导轮播图像

html - 如何制作 CSS 边框线

c# - ASP.NET C# MVC 将值从 Controller 传递到 cshtml

c - 从文件中删除空字符

javascript - 是否可以暂时卡住 HTML 元素的当前外观?

jquery - Chrome 问题 - jQuery SmoothDivScroll

c# - asp.net 文本 onkeyup 事件

c# - 如何从整数值中获取月份名称?

MYSQL:IF语句查找n行中的空列

c - C语言如何判断标识符是否为字符?