1. 程式人生 > >asp.net GridView 表格之選中行

asp.net GridView 表格之選中行

asp.net 技術 行數據 event tar tree lin asc end

技術分享一、GridView 表格之選中行

asp.net選中行的功能最初以為只能通過屬性中AllowGenerateSelectButton(運行時是否自動生成選擇按鈕)來實現,需要點擊生成的選擇按鈕來操作,但這樣使用並是很方便。

技術分享

經尋找找到了改進辦法如下效果

技術分享

鼠標經過時背景色會改變,選中後可獲取響應行的數據

實現方法如下:

技術分享

首先前臺設計屬性框中事件綁定RowDataBound(在對時局進行了綁定後激發)事件

後臺代碼如下:

   /// <summary>
        /// 在對數據進行了綁定後激發
        /// 主要實現鼠標點擊時選中該行
        /// </summary>
/// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { #region 方法0 存在bug 暫未改進 供參考 //e.Row.Attributes["style"] = "cursor:hand"; //PostBackOptions myPostBackOptions = new PostBackOptions(this);
//myPostBackOptions.AutoPostBack = false; //myPostBackOptions.PerformValidation = false; //myPostBackOptions.RequiresJavaScriptProtocol = true; //加入javascript:頭 //String evt = Page.ClientScript.GetPostBackClientHyperlink(sender as GridView, "Select$" + e.Row.RowIndex.ToString());
//e.Row.Attributes.Add("onclick", evt); #endregion #region 方法1 //if (e.Row.RowType == DataControlRowType.DataRow) //{ // e.Row.Attributes.Add("onClick", "__doPostBack(‘" + GridView1.UniqueID + "‘,‘Select$" + e.Row.RowIndex + "‘);");//此處為兩個“_” //} #endregion #region 方法2 int i; for (i = 0; i <= GridView1.Rows.Count; i++) { //首先判斷是否是數據行 if (e.Row.RowType == DataControlRowType.DataRow) { //當鼠標停留時更改背景色 e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor=‘#00A9FF‘"); //當鼠標移開時還原背景色 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c"); //單擊行的任意列會自動選中此行 e.Row.Attributes.Add("onclick", "__doPostBack(‘GridView1‘,‘Select$" + e.Row.RowIndex + "‘)"); } } #endregion

二、獲取選中行數據

選中某行後獲取數據

技術分享技術分享

在屬性框中事件選項中選擇設置SelectedIndexChanged( 在GridView中選擇行時,在該行選擇完成後激發)事件選項

後臺代碼如下

        /// <summary>
        /// 選擇某行時在最左側更新顯示數據詳細
        /// 在DataGriew選擇行時,在該選擇操作完成後激發
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (GridView1.SelectedIndex >= 0)
            {
                ClearTreeNodeChecked(TreeView1.Nodes);
                txtName.Text = GridView1.SelectedRow.Cells[0].Text;
                txtPhone.Text = GridView1.SelectedRow.Cells[1].Text;
                txtSendTime.Text = GridView1.SelectedRow.Cells[2].Text;
                GetUserNodes();
            }
        }

asp.net GridView 表格之選中行