GridView/DataGrid行單擊和雙擊事件實現代碼_.Net教程


功能: 單擊選中行,雙擊打開詳細頁面 
說明:單擊事件(onclick)使用了 setTimeout 延遲,根據實際需要修改延遲時間 ;當雙擊時,通過全局變量 dbl_click 來取消單擊事件的響應 
常見處理行方式會選擇在 RowDataBound/ItemDataBound 中處理,這里我選擇 Page.Render 中處理,至少基於以下考慮 
1、RowDataBound 僅僅在調用 DataBind 之后才會觸發,回發通過 ViewState 創建空件不觸發 假如需要更多的處理,你需要分開部分邏輯到 RowCreated 等事件中 
2、並且我們希望使用 ClientScript.GetPostBackEventReference 和 ClientScript.RegisterForEventValidation 方法 進行安全腳本的注冊,而后者需要在頁的 Render 階段中才能處理 .aspx(直接運行)

<%@ Page Language="C#" %> 
<%@ Import Namespace="System.Data" %>

<%--http://community.csdn.net/Expert/TopicView3.asp?id=5767096--%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void Page_Load(object sender, EventArgs e) 
    { 
        if (!IsPostBack) { 
            LoadGridViewProductData(); 
            LoadDataGridProductData(); 
        } 
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
        /*  
         當然可以在這里進行客戶端腳本綁定, 
         但是,我選擇在重載頁的 Render 方法中處理,因為 
         1. RowDataBound 僅僅在調用 DataBind 之后才會觸發,回發通過 ViewState 創建空件不觸發 
            假如需要更多的處理,你需要分開部分邏輯到 RowCreated 等事件中 
         2. 並且我們希望使用  
            ClientScript.GetPostBackEventReference 和 ClientScript.RegisterForEventValidation 方法 
            進行安全腳本的注冊,而后者需要在頁的 Render 階段中才能處理          
        */ 
    }   

    protected void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e) 
    { 
        // 隱藏輔助按鈕列 
        int cellIndex = 0; 
        e.Item.Cells[cellIndex].Attributes["style"] = "display:none"; 
    }    
     
    void LoadGridViewProductData() 
    { 
        DataTable dt = CreateSampleProductData();

        GridView1.DataSource = dt; 
        GridView1.DataBind();     
    }

    void LoadDataGridProductData() 
    { 
        DataTable dt = CreateSampleProductData();

        DataGrid1.DataSource = dt; 
        DataGrid1.DataBind(); 
    }

    #region sample data

    static DataTable CreateSampleProductData() 
    { 
        DataTable tbl = new DataTable("Products");

        tbl.Columns.Add("ProductID", typeof(int)); 
        tbl.Columns.Add("ProductName", typeof(string));         
        tbl.Columns.Add("UnitPrice", typeof(decimal)); 
        tbl.Columns.Add("CategoryID", typeof(int));

        tbl.Rows.Add(1, "Chai", 18, 1); 
        tbl.Rows.Add(2, "Chang", 19, 1); 
        tbl.Rows.Add(3, "Aniseed Syrup", 10, 2); 
        tbl.Rows.Add(4, "Chef Anton’s Cajun Seasoning", 22, 2); 
        tbl.Rows.Add(5, "Chef Anton’s Gumbo Mix", 21.35, 2); 
        tbl.Rows.Add(47, "Zaanse koeken", 9.5, 3); 
        tbl.Rows.Add(48, "Chocolade", 12.75, 3); 
        tbl.Rows.Add(49, "Maxilaku", 20, 3);        

        return tbl; 
    }

    #endregion       

    protected override void Render(HtmlTextWriter writer) 
    { 
        // GridView 
        foreach (GridViewRow row in GridView1.Rows) { 
            if (row.RowState == DataControlRowState.Edit) { // 編輯狀態 
                row.Attributes.Remove("onclick"); 
                row.Attributes.Remove("ondblclick"); 
                row.Attributes.Remove("style"); 
                row.Attributes["title"] = "編輯行"; 
                continue; 
            } 
            if (row.RowType == DataControlRowType.DataRow) { 
                // 單擊事件,為了響應雙擊事件,需要延遲單擊響應,根據需要可能需要增加延遲 
                // 獲取ASP.NET內置回發腳本函數,返回 __doPostBack(<<EventTarget>>, <<EventArgument>>) 
                // 可直接硬編碼寫入腳本,不推薦                 
                row.Attributes["onclick"] = String.Format("javascript:setTimeout(\"if(dbl_click){{dbl_click=false;}}else{{{0}}};\", 1000*0.3);", ClientScript.GetPostBackEventReference(GridView1, "Select$" + row.RowIndex.ToString(), true)); 
                // 雙擊,設置 dbl_click=true,以取消單擊響應 
                row.Attributes["ondblclick"] = String.Format("javascript:dbl_click=true;window.open(’DummyProductDetail.aspx?productid={0}’);", GridView1.DataKeys[row.RowIndex].Value.ToString()); 
                // 
                row.Attributes["style"] = "cursor:pointer"; 
                row.Attributes["title"] = "單擊選擇行,雙擊打開詳細頁面"; 
            } 
        }

        // DataGrid 
        foreach (DataGridItem item in DataGrid1.Items) { 
            if (item.ItemType == ListItemType.EditItem) { 
                item.Attributes.Remove("onclick"); 
                item.Attributes.Remove("ondblclick"); 
                item.Attributes.Remove("style"); 
                item.Attributes["title"] = "編輯行"; 
                continue; 
            } 
            if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem) { 
                //單擊事件,為了響應雙擊事件,延遲 1 s,根據需要可能需要增加延遲 
                // 獲取輔助的支持回發按鈕 
                // 相對而言, GridView 支持直接將 CommandName 作為 <<EventArgument>> 故不需要輔助按鈕 
                Button btnHiddenPostButton = item.FindControl("btnHiddenPostButton") as Button; 
                item.Attributes["onclick"] = String.Format("javascript:setTimeout(\"if(dbl_click){{dbl_click=false;}}else{{{0}}};\", 1000*0.3);", ClientScript.GetPostBackEventReference(btnHiddenPostButton, null));                 
                // 雙擊 
                // 雙擊,設置 dbl_click=true,以取消單擊響應 
                item.Attributes["ondblclick"] = String.Format("javascript:dbl_click=true;window.open(’DummyProductDetail.aspx?productid={0}’);", DataGrid1.DataKeys[item.ItemIndex].ToString()); 
                 
                // 
                item.Attributes["style"] = "cursor:pointer"; 
                item.Attributes["title"] = "單擊選擇行,雙擊打開詳細頁面"; 
            } 
        }

        base.Render(writer); 
    } 
</script>

<html xmlns="http://www.w3.org/1999/xhtml" > 
<head id="Head1" runat="server"> 
    <title>ASP.NET DEMO15: GridView 行單擊與雙擊事件2</title> 
    <script> 
    // 輔助全局變量,指示是否雙擊 
    var dbl_click = false; 
    </script>     
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div>         
        <h3>功能:</h3> 
            <li>單擊選中行</li> 
            <li>雙擊打開詳細頁面</li>         
        <h3>說明:</h3> 
        <ul> 
            <li>這是<a href="GridView/DataGrid http://www.cnblogs.com/Jinglecat/archive/2007/09/20/900645.html"> ASP.NET DEMO 15: 同時支持行單擊和雙擊事件</a>的改進版本</li>             
            <li>單擊事件(onclick)使用了 setTimeout 延遲,根據實際需要修改延遲時間</li> 
            <li>當雙擊時,通過全局變量 dbl_click 來取消單擊事件的響應</li> 
            <li>常見處理行方式會選擇在 RowDataBound/ItemDataBound 中處理,這里我選擇 Page.Render 中處理,至少基於以下考慮 
                <li style="padding-left:20px; list-style-type:square">RowDataBound 僅僅在調用 DataBind 之后才會觸發,回發通過 ViewState 創建空件不觸發 
            假如需要更多的處理,你需要分開部分邏輯到 RowCreated 等事件中</li>  
                <li style="padding-left:20px; list-style-type:square">並且我們希望使用  
            ClientScript.GetPostBackEventReference 和 ClientScript.RegisterForEventValidation 方法 
            進行安全腳本的注冊,而后者需要在頁的 Render 階段中才能處理</li> 
            </li> 
            <li>關於“DataGrid中采取的輔助按鈕支持回發”見<a href="http://www.cnblogs.com/Jinglecat/archive/2007/07/15/818394.html">ASP.NET DEMO8: 為 GridView 每行添加服務器事件</a> 
        </ul> 
        <br /> 
        <input type="button" id="Button1" value="Rebind" onclick="location.href=location.href;" /> 
        <div style="float:left"> 
        <h3>GridView Version</h3> 
        <asp:GridView ID="GridView1" DataKeyNames="ProductID" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound"> 
            <SelectedRowStyle BackColor="CadetBlue" /> 
            <Columns>                                           
                <asp:TemplateField HeaderText="ProductName" >                                 
                    <ItemTemplate>                     
                        <%# Eval("ProductName") %> 
                    </ItemTemplate> 
                    <EditItemTemplate> 
                        <asp:TextBox ID="txtProductName" runat="server" Text=’<%# Bind("ProductName") %>’ /> 
                    </EditItemTemplate> 
                </asp:TemplateField> 
                <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" />                 
            </Columns> 
        </asp:GridView></div> 
        <div style="float:left;padding-left:100px;"> 
        <h3>DataGrid Version</h3> 
        <asp:DataGrid ID="DataGrid1" DataKeyField="ProductID"  runat="server" AutoGenerateColumns="False" OnItemDataBound="DataGrid1_ItemDataBound"> 
        <SelectedItemStyle BackColor="CadetBlue" /> 
            <Columns>              
                <asp:TemplateColumn> 
                    <ItemTemplate> 
                        <asp:Button ID="btnHiddenPostButton" CommandName="Select" runat="server" Text="HiddenPostButton" style="display:none" /> 
                    </ItemTemplate> 
                </asp:TemplateColumn>           
                <asp:BoundColumn DataField="ProductName" HeaderText="ProductName" /> 
                <asp:BoundColumn DataField="UnitPrice" HeaderText="UnitPrice" />  
            </Columns> 
        </asp:DataGrid></div> 
        </li> 
        </div> 
    </form> 
</body> 
</html>

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM