2011-05-11 80 views
6

我對GridView中的ButtonField(圖像類型)背後的命令有個疑問。GridView ButtonField後面的命令

得到了一個名爲gvIngevuld的GridView,以顯示數據行和1個ButtonField行。 現在我必須將這些按鈕後面的代碼(每個都相同)放在一些PDF格式的東西。 問題是我不知道如何把代碼放在這些按鈕後面? 的代碼,我有:

<asp:ButtonField ButtonType="Image" ImageUrl="~/Images/pdf.png" CommandName="pdf_click" /> 

正如你可以看到我用的CommandName =「pdf_click」屬性,但是當我點擊一個按鈕這裏只有一個回傳,但沒有任何反應。 任何人誰可以幫我在這裏?

在需要的情況下,後面的代碼:

protected void pdf_click(object sender, EventArgs e) 
{ 
    lblWelkom.Text = "Succes!"; 
} 

感謝。

+0

嘗試將CommandName更改爲onclick並查看是否修復了它。另外,可能需要將runat =「server」添加到它。我知道我們做了一個隱藏的按鈕,但那只是我們用它來連接的具體方式。 – Robert 2011-05-11 12:09:55

回答

28

您應該使用gridview的事件RowCommand。將commandArgument設置爲您項目的唯一鍵。 (默認情況下,它通過行的索引)

void gvIngevuld_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=="pdf_click") 
    { 
    // 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 = gvIngevuld.Rows[index]; 
    //gbIngevuld is your GridView's name 

    // Now you have access to the gridviewrow. 
    } 
} 

此外,如果已經設置在GridView的DataKeyNames,您可以通過以下方式訪問它:

int index = Convert.ToInt32(e.CommandArgument); 
    int ServerID = Convert.ToInt32(GridView1.DataKeys[index].Value); 
0

CommandName屬性沒有定義方法來調用。爲此,您需要創建一個綁定到控件的命令事件的方法。
我不太瞭解GridViews,但我認爲最簡單的方法是在Visual Studio的設計視圖中選擇它,轉到屬性,單擊事件按鈕(看起來像閃電),然後雙擊RowCommand事件propety。這應該會自動創建一個綁定到命令按鈕事件的方法。
然後,您可以使用GridViewCommandEventArgs參數來訪問CommandName,CommandArgument和CommandSource屬性,以確定哪個按鈕導致事件觸發。

0

只是一個另外,我寫了,並試圖完全一樣的,但是按鈕仍然沒有工作...

...它花了一些時間,直到我意識到,我忘了一件事,這是 OnRowCommand="<YourGridViewName>_RowCommand" 內您的GridView元素在** .cs *文件中