listview ItemCommand不启动

时间:2011-01-11 08:20:43

标签: c# .net asp.net button

当我在列表视图中按任意链接按钮时,它根本不会启动

<div>
   <%
      String[] d1 = { "1", "2", "3" };
      String[] d2 = { "4", "5", "6", "7" };
      ListView1.DataSource = d1;
      ListView1.DataBind();
      ListView2.DataSource = d2;
      ListView2.DataBind();
   %>
   <asp:ListView ID="ListView1" runat="server" OnItemCommand="lv_command">
      <LayoutTemplate>
          <ul>
              <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
          </ul>
      </LayoutTemplate>
      <ItemTemplate>
          <asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>
      </ItemTemplate>
   </asp:ListView>
   <asp:ListView ID="ListView2" runat="server" OnItemCommand="lv_command">
      <LayoutTemplate>
          <ul>
              <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
          </ul>
      </LayoutTemplate>
      <ItemTemplate>
          <asp:LinkButton ID="LinkButton2" runat="server">LinkButton</asp:LinkButton>
      </ItemTemplate>
   </asp:ListView>
</div>

protected void lv_command(object sender, ListViewCommandEventArgs e)
{
  int i = 0;
}

2 个答案:

答案 0 :(得分:2)

设置每个LinkBut​​tons的CommandName属性,例如:

 <asp:LinkButton ID="LinkButton1" runat="server" CommandName="MyCommand">LinkButton</asp:LinkButton>

因此,当引发ItemCommand事件时,您可以检测是否从链接按钮触发它,如下所示:

     protected void lv_command(object sender, ListViewCommandEventArgs e)
    {
  if(e.CommandName == "MyCommand")
  {
    //do something
  }
}

此外,仅在初始加载时绑定listview并在需要时再次从某些事件处理程序绑定它更具性能:

    protected void Page_Load(object sender, EventArgs e)
{
   if(!Page.IsPostBack)
   {
    String[] d1 = { "1", "2", "3" };
    String[] d2 = { "4", "5", "6", "7" };
    ListView1.DataSource = d1;
    ListView1.DataBind();
    ListView2.DataSource = d2;
    ListView2.DataBind();
   }
}

答案 1 :(得分:0)

将执行数据绑定的逻辑移动到代码隐藏中:

protected void Page_Load(object sender, EventArgs e)
{
    String[] d1 = { "1", "2", "3" };
    String[] d2 = { "4", "5", "6", "7" };
    ListView1.DataSource = d1;
    ListView1.DataBind();
    ListView2.DataSource = d2;
    ListView2.DataBind();
}

protected void lv_command(object sender, ListViewCommandEventArgs e)
{
  int i = 0;
}