2016-10-11 50 views
3
r.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink((Control)this.gridView, "Select$" + r.RowIndex); 

嗨,我使用上面的代码来捕获在Asp.net中的GridView中的行上的单击事件。此代码的工作原理,我能够捕获OnSelectdIndexChanged中新选择的行,但回发也导致整个页面刷新。如何取消由Page.ClientScript.GetPostBackClientHyperlink引起的页面刷新?

有什么办法可以取消页面刷新,但仍然可以在不添加'select'按钮的情况下更改选定的行吗?

+1

你想对“新选择的行”做什么?如果你需要在代码后面完成某些事情,你需要回传。如果是这样,你可以使用[UpdatePanel](https://msdn.microsoft.com/en-us/library/bb399001.aspx)。如果你需要在前端做某些事情,那么只能采取另一种方法。 – VDWWD

+0

我只需要知道哪个索引被点击了,所以我可以去选择的项目的详细页面,如果页面刷新它做了几个API调用,这减慢了网站的速度,我会看看更新面板,谢谢 – Litrico

回答

2

您需要GridView中的RowCreated事件才能这样做。请参见下面的示例:

protected void GridView1_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) { 
     e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';"; 
     e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';"; 
     e.Row.ToolTip = "Click to select row"; 
     e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex); 
    } 
} 

你可以看到这个链接了解更多关于选择行,而不选择按钮 - How to implement full row selecting in GridView without select button?

为防止回传,我会建议使用的UpdatePanel我前面的评论,然后删除。下面是将GridView放入UpdatePanel的示例:

<asp:ScriptManager ID=" ScriptManager1" runat="server"/> 
    <asp:UpdatePanel ID=" UpdatePanel1" runat="server"> 
     <ContentTemplate> 
      <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"> 
      </asp:GridView> 
     </ContentTemplate> 
    </asp:UpdatePanel> 

这是一段代码。所以我在评论部分分享了一个链接。请检查。

+0

感谢您的回答,但这是我正在做的。回帖会导致页面刷新,但我想取消该刷新,或者只是确保它不会以某种方式发生。 – Litrico

+0

不要紧,因为后期回复。我正在考虑UpdatePanel。请参阅此链接 - http://csharpdotnetfreak.blogspot.com/2012/08/select-gridview-row-onclick-of-cell-javascript.html?m=1让我知道。 –

+0

感谢您的帮助,我会看看更新面板! – Litrico

1

您可以使用OnRowDataBound事件向GridView添加属性。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     if (e.Row.RowType == DataControlRowType.DataRow) 
     { 
      //add the current row number 
      e.Row.Attributes.Add("rowNumber", e.Row.RowIndex.ToString()); 

      //add an item from the database 
      e.Row.Attributes.Add("itemID", DataBinder.Eval(e.Row.DataItem, "database_id").ToString()); 

      //or add a click directy and redirect with javascript 
      e.Row.Attributes.Add("onclick", "location.href='/newPage.aspx?id=" + DataBinder.Eval(e.Row.DataItem, "database_id").ToString() + "'"); 
     } 
    } 

如果你没有使用我的代码片段中的第三个属性,你需要处理行点击clientside。你可以用jQuery来做到这一点。

<script type="text/javascript"> 
     $(document).ready(function() { 
      $("#<%= GridView1.ClientID %> tr").click(function() { 
       var rowNumber = $(this).attr("rowNumber"); 
       var itemID = $(this).attr("itemID"); 
       alert("This is row number: " + rowNumber + ". It has ID: " + itemID); 
      }) 
     }); 
    </script>