我希望以编程方式向 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";
}
}
而且效果很好。然而,在交替的行上添加了“IsActive”类,我最终得到以下 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() 中,但我不知道在哪里。谁能给我指点一下吗?
你可以照顾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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)