使用JavaScript选择GridView行的方法汇总(Select row of GridView by JavaScript)
先说说我的方法吧,不是最好的,却是代码量最少的
一行:
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.gvUsers, "select$" + e.Row.RowIndex);
呵呵有点夸张了,具体做法是在GridView的RowDataBound事件里写这么写:
protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.gvUsers, "select$" + e.Row.RowIndex);
e.Row.Attributes["style"] = "cursor:pointer";
}
{
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.gvUsers, "select$" + e.Row.RowIndex);
e.Row.Attributes["style"] = "cursor:pointer";
}
原理很简单,在ASP.NET的页面Render时,GridView的选择、删除、编辑 等事件会产生简单的postback 参数,分别是select$, Update$, Edit$...
这样就给我们带来了很大的便利,在上面的例子中,就使用了Select$方式
与这个方法类似或几乎相同的还有:
来自http://www.cnblogs.com/xioxu/articles/473369.html的:(这位园友添加了RowType的判断,good!)
protected void grdView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onClick", "javascript:__doPostBack('"+grdView.ID+"','Select$"+e.Row.RowIndex+"');");
}
}
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onClick", "javascript:__doPostBack('"+grdView.ID+"','Select$"+e.Row.RowIndex+"');");
}
}
来自http://www.cnblogs.com/easydata/articles/924947.html的:(确实,我们还可以像这位园友一样,给Row添加许多客户端效果,比如onmouseover之类的)
protected override void Render(HtmlTextWriter writer)
{
foreach (GridViewRow Row in GridView1.Rows)
{
if (Row.RowType == DataControlRowType.DataRow)
{
Row.Attributes["ondblclick"] = ClientScript.GetPostBackEventReference(GridView1, "Select$" + Row.RowIndex.ToString(), true);
Row.Attributes["style"] = "cursor:pointer";
Row.Attributes["title"] = "双击选择行";
}
}
base.Render(writer);
}
{
foreach (GridViewRow Row in GridView1.Rows)
{
if (Row.RowType == DataControlRowType.DataRow)
{
Row.Attributes["ondblclick"] = ClientScript.GetPostBackEventReference(GridView1, "Select$" + Row.RowIndex.ToString(), true);
Row.Attributes["style"] = "cursor:pointer";
Row.Attributes["title"] = "双击选择行";
}
}
base.Render(writer);
}
OK,上面的做法都是通过JavaScript实现,但还是发生了PostBack,如果想实现完全的AJAX选取,还是请参考李永京前辈的文章:
http://www.cnblogs.com/lyj/archive/2008/05/10/1191275.html
其原理是借助HiddenField来实现客户端的"Select"(不是真正的select了那一行..)