2012-12-06 34 views
2

第一個問題:從模板字段按鈕獲取GridView行索引

我有一個gridview'gvSnacks',包含零食和價格列表。 gridview的第一列是一個帶有'btnAdd'按鈕的模板字段。

當單擊其中一個添加按鈕時,我希望它將該行的值分配給一個整數,以便我可以從該行檢索其他數據。

這是我的,但我已經死了。

protected void btnAdd_Click(object sender, EventArgs e) 
{ 
    int intRow = gvSnacks.SelectedRow.RowIndex; 

    string strDescription = gvSnacks.Rows[intRow].Cells[2].Text; 
    string strPrice = gvSnacks.Rows[intRow].Cells[3].Text; 
} 

感謝任何幫助!

+0

什麼是你的問題? – ean5533

+0

問題是如何在點擊添加按鈕之一時將gridview行分配給整數? – pshotwell

+0

你目前的代碼有什麼問題? – codingbiz

回答

4

您可能需要使用RowCommand事件:

public event GridViewCommandEventHandler RowCommand 

This is the MSDN link for this event

按鈕必須具有的CommandName屬性,你可以把該行的值在命令參數:

void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e) 
    { 
    // If multiple buttons are used in a GridView control, use the 
    // CommandName property to determine which button was clicked. 
    if(e.CommandName=="Add") 
    { 
     // Convert the row index stored in the CommandArgument 
     // property to an Integer. 
     int index = Convert.ToInt32(e.CommandArgument); 

     // Retrieve the row that contains the button clicked 
     // by the user from the Rows collection. 
     GridViewRow row = ContactsGridView.Rows[index]; 

     // Create a new ListItem object for the contact in the row.  
     ListItem item = new ListItem(); 
     item.Text = Server.HtmlDecode(row.Cells[2].Text) + " " + 
     Server.HtmlDecode(row.Cells[3].Text); 

     // If the contact is not already in the ListBox, add the ListItem 
     // object to the Items collection of the ListBox control. 
     if (!ContactsListBox.Items.Contains(item)) 
     { 
     ContactsListBox.Items.Add(item); 
     } 
    } 
    }  
+0

欣賞這個!我真的很喜歡在一個rowcommand下處理不同參數的能力! – pshotwell