将第二个类添加到RowDataBound

时间:2017-02-22 14:00:24

标签: c# asp.net gridview

我希望以编程方式向GridView添加一个额外的类。我知道我可以使用以下代码执行此操作:

public void RowDataBound(object sender, GridViewRowEventArgs e)
{
    DataRow row = ((DataRowView)e.Row.DataItem).Row;
    if (!row.Field<Boolean>("IsActive"))
    {
        e.Row.Attributes["class"] += "InActive";
    }
}

它工作正常。课程&#34; IsActive&#34;但是,在交替的行中我添加了这个HTML:

<tr class="gvAlternatingStyle" class="InActive"
    onmouseover="gvMouseOver(this)" 
    onmouseout="gvMouseOut(this)" style="cursor:pointer;">

两个类定义不是我想要的。我更喜欢这样的东西:

<tr class="gvAlternatingStyle InActive"
    onmouseover="gvMouseOver(this)" 
    onmouseout="gvMouseOut(this)" style="cursor:pointer;">

当然更有效。

我似乎无法弄清楚在哪里/如何调整这个HTML。可能在OnPreRender()但我不知道在哪里。谁能给我一个指针?

2 个答案:

答案 0 :(得分:1)

您可以自己处理AlternatingRowStyle-CssClass并在需要时添加额外的课程。当然,您需要将它从GridView标题中删除。

string AlternatingRowStyleCssClass;

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //check if the row is a datarow
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string myClass = string.Empty;

        //get the AlternatingRowStyle-CssClass for reference into a variable and delete from the gridview itself
        if (e.Row.RowIndex == 0)
        {
            AlternatingRowStyleCssClass = GridView1.AlternatingRowStyle.CssClass;
            GridView1.AlternatingRowStyle.CssClass = "";
        }

        //check if the row is alternate, if so set the alternating class
        if (e.Row.RowIndex % 2 == 1)
        {
            myClass = AlternatingRowStyleCssClass;
        }

        //check if you need to add the extra class
        DataRow row = ((DataRowView)e.Row.DataItem).Row;
        if (!row.Field<Boolean>("IsActive"))
        {
            myClass += " Inactive";
        }

        //add all the classes to the row
        e.Row.Attributes["class"] = myClass.Trim();
    }

    //add the class to the gridview again (maybe relevant for postback)
    if (e.Row.RowType == DataControlRowType.Footer)
    {
        GridView1.AlternatingRowStyle.CssClass = AlternatingRowStyleCssClass;
    }
}

答案 1 :(得分:1)

经过一段时间的混乱并在VDWWD的帮助下,我通过上述和OnPreRender()的组合研究了如何实现这一目标:

    public void RowDataBound(object sender, GridViewRowEventArgs e)
    {
            DataRow row = ((DataRowView)e.Row.DataItem).Row;
            if (!row.Field<Boolean>("IsActive"))               {
                e.Row.Attributes["class"] += "InActive";                
    }


    protected void PreRender(object sender, EventArgs e)
    {
        foreach(GridViewRow row in GridView1.Rows)
        {
            if ((row.Attributes["class"] == "InActive")&& 
                (row.RowState == DataControlRowState.Alternate)){
                row.RowState = DataControlRowState.Normal;
                row.Attributes["class"] = "gvAlternatingStyle InActive";

            }

        }
    }