2012-02-27 49 views
8

我试图有一个onclick事件添加到行,一旦数据绑定到一个gridview的webcontrol。下面的代码没有添加任何属性(一旦创建页面就检查了viewsource),当然,没有添加功能。现在,我刚刚在页面上进行了onclick打印,但最终它会链接到另一个页面。有什么错误的想法?ASP.NET的gridview行onclick

此外,感谢整个stackoverflow社区。这个社区一直是一个很好的帮助。本周末计划自己通过一些帖子,并开始回答问题,因为我可以回馈一些。

C#服务器端

protected void dataTbl_RowDataBound(GridViewRowEventArgs e){ 
      e.Row.Attributes.Add("id",e.Row.Cells[0].Text); 
      e.Row.Attributes.Add("onclick", "rowClick('"+e.Row.RowIndex+"')"); 

     } 

JavaScript客户端

function rowClicked(counter){ 
    document.write(counter); 
} 

回答

9

我使用这在我的GridView的的RowDataBound,添加的特性来选择该行:

protected void grvSearch_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    try 
    { 
     switch (e.Row.RowType) 
     { 
      case DataControlRowType.Header: 
       //... 
       break; 
      case DataControlRowType.DataRow: 
       e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#93A3B0'; this.style.color='White'; this.style.cursor='pointer'"); 
       if (e.Row.RowState == DataControlRowState.Alternate) 
       { 
        e.Row.Attributes.Add("onmouseout", String.Format("this.style.color='Black';this.style.backgroundColor='{0}';", grvSearch.AlternatingRowStyle.BackColor.ToKnownColor())); 
       } 
       else 
       { 
        e.Row.Attributes.Add("onmouseout", String.Format("this.style.color='Black';this.style.backgroundColor='{0}';", grvSearch.RowStyle.BackColor.ToKnownColor())); 
       } 
       e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(grvSearch, "Select$" + e.Row.RowIndex.ToString())); 
       break; 
     } 
    } 
    catch 
    { 
     //...throw 
    } 
} 

而这个用来捕捉de事件,当用户点击该行时:

protected void grvSearch_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    try 
    { 
     //Do wherever you want with grvSearch.SelectedIndex     
    } 
    catch 
    { 
     //...throw 
    } 
} 
+0

看起来你正在使用onclick事件服务器端。我正在使用我的onclick事件连接javascript方法。第一个问题是,它甚至没有添加数据绑定的属性,我相信我使用的是与你相同的方法。你看到我的方法和你的方法有什么不同吗? – steventnorris 2012-02-27 17:24:16

+0

是的,这是一个服务器端的onclick。如果你需要javascript onclick,我建议你验证你的事件(RowDataBound)。你的GridView包含事件?像'code'grv.RowDataBound + = dataTbl_RowDataBound'code'?因为这两种方法非常相似。 – 2012-02-27 17:55:22

+0

......我觉得很愚蠢。谢谢你指出明显的。如果事件甚至不知道这样做,很难调用方法。 – steventnorris 2012-02-27 18:15:39

3

要在jQuery的做到这一点,只是得到这样的行单击事件:

$(document).ready(function() { 
    var clickCnt = 0; 
    $('table tr').click(function(){ 
     clickCnt++; 
     //Do something 
    }); 
}); 

就这样,我建议在TR ID设置主键的对象显示在该行。

3

是否设置Grid来调用dataTbl_RowDataBound事件?如果您在该事件中使用断点进行调试,那么该事件是否会被解雇?

+0

而小错误的愚蠢做出。我在我的活动电话中遇到问题。谢谢。 – steventnorris 2012-02-27 18:16:16