2012-05-28 97 views
9

我需要從RowCommand事件中獲取單元格的值,但該值不在GridView的PrimaryKeyNames參數中。在RowCommand中獲取GridView單元格的值

目前我有:

if (e.CommandName == "DeleteBanner") 
     { 
      GridViewRow row = gvCurrentPubBanner.SelectedRow; 
      string BannerName = row.Cells[1].Text; 

這不起作用(索引超出範圍錯誤的),我也試着:

int index = Convert.ToInt32(e.CommandArgument); 
GridViewRow row = gvCurrentBanners.Rows[index]; 

這不起作用,無論是作爲CommandArgument (橫幅ID)不是行ID。

回答

10
Dim row As GridViewRow = CType(CType(e.CommandSource, Control).NamingContainer, GridViewRow) 

然後獲取鍵或獲取單元格並將其轉換爲數據控件字段。

Dim id As Guid = GridView1.DataKeys(row.RowIndex).Value 

Dim email As String = CType(row.Cells(2), DataControlFieldCell).Text 

備註:這隻適用於Boundfields。

+0

解決'asp:TemplateField - ItemTemplate'? – Kiquenet

+0

參考@Chưabiết答案爲Itemtemplate字段。 –

1
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) 
    { 
     if (e.CommandName == "Edit_Mob") { 

     GridViewRow row = (GridViewRow (((ImageButton)e.CommandSource).NamingContainer); 

     int RowIndex = row.RowIndex; // this find the index of row 

     int varName1 = Convert.ToInt32(((Label)row.FindControl("lbl_mobile_id")).Text.ToString()); //this store the value in varName1 

     } 
    } 
3

試試這一個..

GridViewRow gvRow = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer); 
int rowIndex=gvRow.RowIndex 
+0

我沒有看到這是如何工作的,因爲你正在創建一個新的GridviewRow,而不是引用現有的gridview – Fandango68

2

INT指數= Convert.ToInt32(e.CommandArgument);

只有當你在GridView的使用按鈕的工作

<Columns> 
    <asp:ButtonField ButtonType="Button" Text="Save" CommandName="Select" /> 
</Columns> 

我不知道這是正確的,但對我來說

+2

這是正確的解決方案,正如[RowCommand中的MSDN頁面]上記錄的那樣(http:// msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand%28v=vs.110%29.aspx):_ ButtonField類自動使用適當的索引值填充CommandArgument屬性._ – marapet

3

@Romil工作:在C#代碼:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) 
{ 
    GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer); 
    int id = (int)GridView1.DataKeys[row.RowIndex].Value; 
} 

(LinkBut​​ton是模板字段中的按鈕)。

+1

對'asp:TemplateField - ItemTemplate'有效 – Kiquenet

相關問題