如何在GridView的RowCommand事件中獲取當前的GridViewRow

由於事件參數 GridViewCommandEventArgs 並不公開Row屬性指示當前行,(DataGridCommandEventArgs 公開 Item 屬性以獲取當然 DataGridItem,不知 ASP.NET Team 是如何考慮這一設計的),因此需要一點“技巧”來獲取此屬性。

其實這是一個早就已知的問題,鑑於CSDN裏面每每有人疑惑,這裏稍微整理下,便於參閱:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    
...{
        
int rowIndex = -1;
         GridViewRow row
= null;        
        
switch (e.CommandName) ...{
            
case "Command1": // 模板列
                
// 對於模板列內的按鈕,我們需要顯示綁定行索引到按鈕的 CommandArgument 屬性
                
// 以獲取觸發事件的行信息
                 rowIndex = Convert.ToInt32(e.CommandArgument);
                 row
= GridView1.Rows[rowIndex];                
                 DisplayInfo(row, e.CommandName);
                
// your codes
                
//
                break;
            
case "Command2": // 模板列
                
// 同樣處於模板列中,但不採用 Command1 方式,而是通過 NamingContrainer 屬性
                
// 直接獲取當前的 GridViewRow
                 Control cmdControl = e.CommandSource as Control; // 表示觸發事件的 IButtonControl,保持統一性並便於後續操作,我們這裏直接轉化爲控件基類 Control
                 row = cmdControl.NamingContainer as GridViewRow;
                 DisplayInfo(row, e.CommandName);
                
// your codes
                
//
                break;
            
case "Command3": // 綁定列
                
// 對於 ButtonField 列,數據源控件內部自動以適當的項索引值填充 CommandArgument 屬性。
                
// 而無需我們顯示綁定其 CommandArgument 屬性                
                
// 注意,我們這裏無法採用 Command2 的方式,對於 BUttonField 觸發的事件,
                
// GridViewCommandEventArgs.CommandSource 表示的包含此按鈕的 GridView
                 rowIndex = Convert.ToInt32(e.CommandArgument);
                 row
= GridView1.Rows[rowIndex];
                 DisplayInfo(row, e.CommandName);
                
// your codes
                
//
                break;
         }

     }
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章