使用JavaScript選擇GridView行的方法匯總(Select row of GridView by JavaScript)

來源:互聯網
上載者:User

先說說我的方法吧,不是最好的,卻是代碼量最少的

 

一行:

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";
    }

 

原理很簡單,在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+"');");
    }
}

 

來自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);
    }

 

 

OK,上面的做法都是通過JavaScript實現,但還是發生了PostBack,如果想實現完全的AJAX選取,還是請參考李永京前輩的文章:

http://www.cnblogs.com/lyj/archive/2008/05/10/1191275.html

其原理是藉助HiddenField來實現用戶端的"Select"(不是真正的select了那一行..)

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.