簡體   English   中英

listview OnItemCommand沒有啟動

[英]listview OnItemCommand dosen't fire up

當我按下列表視圖中的任一鏈接按鈕時,它根本不會啟動

<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;
}

設置每個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();
   }
}

將執行數據綁定的邏輯移到后面的代碼中:

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM