利用JavaScript选择GridView行


 当我们想在GridView中添加删除、选择功能时,我们通常的做法是利用模板功能在每行添加一个按钮控件或者超链接按钮控件,单击按钮利用RowCommand获取每行的ID。

  下面我们利用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);
}

  好了,这个技巧就介绍到这里了,大家试一试!


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3