其實這是一個早就已知的問題,鑑於CSDN裏面每每有人疑惑,這裏稍微整理下,便於參閱:
{
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;
}
}