2009-09-11 78 views
0

使用ASPNET設置一個動態創建按鈕的CommandArgument,C#3.5中VS2008:在GridView或ListView

我已經成功使用了下面的代碼在GridView或ListView模板列:

<asp:Button ID="btnShow" runat="server" Text="?" 
    TabIndex="-1" CommandName="ShowDefinition" 
    CommandArgument='<%# Eval("PKey") %>' /> 

隨着代碼在後面獲取點擊該按鈕的行的標識符。 :

protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e) 
{ 
    if (e.CommandName == "ShowDefinition") 
     { 
     int showRecordPKey = Convert.ToInt32(e.CommandArgument); 
     } 
} 

現在我試圖動態(有條件地)把該按鈕放在列中。

我嘗試使用佔位符用下面的代碼後面這樣做:

public class BtnShow 
{ 
    public Button btnShow = new Button(); 
    PlaceHolder ph = new PlaceHolder(); 
    public BtnShow(string commandName,string displayText, PlaceHolder ph) 
    { 
     btnShow.ID = "btnShow"; 
     btnShow.Text = "?"; 
     btnShow.TabIndex = -1 ; 
     btnShow.CommandName = "ShowDefinition"; 
     btnShow.CommandArgument = "(<%# Eval('PKey') %>" ; 
     this.ph = ph; 
    } 
public void AddQuMarkToPlaceholder() 
{ 
    ph.Controls.Add(btnShow); 
} 

時,將生成按鈕,但命令參數不計算,字符串 「(<%#的eval(‘PKEY’) %>」作爲命令參數傳遞

我怎麼做我想做

回答

1

使用RowCommand代替ItemCommand,這個工作:?

protected void ListView1_RowCommand(object sender, GridViewCommandEventArgs e) 
    { 
     GridViewRow row = (GridViewRow) 
       (((Button) e.CommandSource).NamingContainer); 
     Label pk = (Label) row.FindControl("lblPKey"); 
     int showRecordPKey = Convert.ToInt32(pk.Text); 
    }