利用JavaScript選擇GridView行

來源:互聯網
上載者:User

本篇技巧和訣竅記錄的是:利用JavaScript選擇GridView行。

下面我們利用JavaScript完成這一功能。

我們可以通過調用JavaScirpt函數改變單擊的行的背景顏色來類比選擇的行 ,這裡需要聲明一個隱藏欄位,從JS中獲得選取GridView行的ID。在選擇/刪除 事件中,可以從隱藏欄位中得到選擇行的ID,完成一些需要功能。

第一步:在頁面中添加GridView控制項和一個按鈕,隱藏欄位

<input id="hdnEmailID" type="hidden"
    value="0" runat="server" name="hdnEmailID" />
<asp:GridView ID="gvUsers" runat="server"
       AutoGenerateColumns="False"
       OnRowDataBound="gvUsers_RowDataBound">
  <Columns>
    <asp:BoundField DataField="Email" HeaderText="郵件" ReadOnly="True" />
    <asp:BoundField DataField="Name" HeaderText="姓名" ReadOnly="True" />
  </Columns>
</asp:GridView>
<asp:Button ID="btnSelect" runat="server"
      OnClick="btnSelect_Click" Text="Select" />

第二步:編寫JS函數來擷取選擇行的id,並改變背景顏色

<script language="javascript" type="text/javascript">
  var lastRowSelected;
  var originalColor;
  function GridView_selectRow(row, EmailID)
  {
     var hdn=document.form1.hdnEmailID;
     hdn.value = EmailID;
     if (lastRowSelected != row)
      {
      if (lastRowSelected != null)
       {
       lastRowSelected.style.backgroundColor = originalColor;
       lastRowSelected.style.color = 'Black'
       lastRowSelected.style.fontWeight = 'normal';
       }
     originalColor = row.style.backgroundColor
     row.style.backgroundColor = 'BLACK'
     row.style.color = 'White'
     row.style.fontWeight = 'normal'
     lastRowSelected = row;
     }
  }
  function GridView_mouseHover(row)
  {
    row.style.cursor = 'hand';
  }
</script>

略過一步,就是綁定資料,大家自行完成。

第三步:在RowDataBound事件中添加JS函數調用。

protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    e.Row.ID = e.Row.Cells[0].Text;
    e.Row.Attributes.Add("onclick",
      "GridView_selectRow(this,'" + e.Row.Cells [0].Text + "')");
    e.Row.Attributes.Add("onmouseover", "GridView_mouseHover(this)");
  }
}

第四步:完成按鈕事件

在選擇/刪除按鈕單擊事件我們可以用hdnEmailID.Value方式獲得行的id。然 後利用id來完成操作;這裡為了示範,我只是輸出了這個值。

protected void btnSelect_Click(object sender, EventArgs e)
{
  Response.Write(hdnEmailID.Value);
}

好了,這個技巧就介紹到這裡了,大家試一試!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.