2009-09-11 81 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); 
    }