2012-02-27 40 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