簡體   English   中英

按鈕觸發事件,按鈕陣列未觸發

[英]Button click event for array of buttons not firing

我認為這個問題已經被問過很多次了(我自己問過一次),但是我面臨着一個新問題。我在應用程序中的另一個按鈕上單擊時創建了一個按鈕數組。創建的按鈕數量取決於根據我從數據庫中獲取的值和我從數據庫中獲取的值取決於我在查詢中傳遞的會話值。我的代碼如下。

代碼

   protected void attributes()
    {
     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
    SqlCommand cmd = new SqlCommand("select attributesequenceNumber as attsno,ProductCode as pcode, P26 as '" + 26 + "',P28 as '" + 28 + "',P30 as '" + 30 + "',P32 as '" + 32 + "',P34 as '"+34+"',P36 as '"+36+"',P38 as '"+38+"',P40 as '"+40+"',P42 as '"+42+"',SHXS as XS,SHS as S,SHM as M,SHL as L,SHXL as XL,SHXXL as XXL from tblattribute where ProductCode='" + Session["ImgProdCode"] + "'", con);
    //SqlCommand cmd = new SqlCommand("select Col.value('local-name(.)', 'varchar(Max)') as ColName from (select * from tblattribute where ProductCode ='"+Session["ImgProdCode"]+"' for xml path(''), type) as T(XMLCol) cross apply T.XMLCol.nodes('*') as n(Col) where Col.value('.', 'varchar(1)') = 1 " , con);
    try
    {
        con.Open();
        cmd.ExecuteNonQuery();
        DataTable dtble = new DataTable();
        SqlDataAdapter dap = new SqlDataAdapter(cmd);
        dap.Fill(dtble);
        if (dtble.Rows.Count > 0)
        {
           result = dtble.Columns.Cast<DataColumn>()
        .Where(c => c.ColumnName != "pcode" && c.ColumnName != "attsno")
        .Where(c => dtble.Rows[0][c].ToString() == "1")
        .Select(c => c.ColumnName)
        .ToList();
            res = result.Count;
            lbl = new Button[res];
            for(i=0; i<result.Count; i++)
            {

                lbl[i] = new Button();
                lbl[i].Text = result[i];
                lbl[i].ID = "btn" + i.ToString();
                lbl[i].Width = 30;
                lbl[i].Click+=new EventHandler(lbl_click);
                lbl[i].CssClass = "label";
                div1.Controls.Add(lbl[i]);
            }

        }

    }
    catch
    {
        throw;
    }
    finally
    {
        if (con != null)
        {
            con.Close();
        }
    }

} 

protected void lbl_click(object sender, EventArgs e)
{

    Button lbl = sender as Button;
    lbl.CssClass = "label1";

}

上面的方法attribute()將在按鈕單擊時被調用,並且會話值也將在buttonclick上生成。在研究中,我知道應該在page_init事件中完成動態按鈕的創建,但是我不能在這里進行。請幫助解決此問題。

在這里看看。

http://blog.krisvandermast.com/AddingADynamicControlToAPlaceholderControlAndWireUpTheEvent.aspx

該事件在那里,您只需要重新連接即可。

您可以使用jQuery來實現。
向網頁添加jQuery參考
獲取適合類'label'的所有控件,在其click事件上調用服務器端'lbl_click'方法。
確保將“ lbl_click”方法標記為靜態,並用[webmethod]裝飾。

Aspx頁面

<script src="http://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
//Find all controls that belongs to class '.label'
//on its click event call the server side function.
  $(".label").click(function(e) {
    $.ajax({
      type: "POST",
      url: "Default.aspx/lbl_click",
      data: "{}", //can pass parameter here, if required
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      error:
      function(XMLHttpRequest, textStatus, errorThrown) {
        //Handle error here.
      },
      success:
      function(result) {
      //Set button css class to 'label1' using jQuery.
      }
    });
  });
});
</script>
</head>


背后的代碼

  protected void attributes()
  {
   SqlConnection con = new 

SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
    SqlCommand cmd = new SqlCommand("select attributesequenceNumber as attsno,ProductCode as pcode, P26 as '" + 26 + "',P28 as '" + 28 + "',P30 as '" + 30 + "',P32 as '" + 32 + "',P34 as '" + 34 + "',P36 as '" + 36 + "',P38 as '" + 38 + "',P40 as '" + 40 + "',P42 as '" + 42 + "',SHXS as XS,SHS as S,SHM as M,SHL as L,SHXL as XL,SHXXL as XXL from tblattribute where ProductCode='" + Session["ImgProdCode"] + "'", con);
    //SqlCommand cmd = new SqlCommand("select Col.value('local-name(.)', 'varchar(Max)') as ColName from (select * from tblattribute where ProductCode ='"+Session["ImgProdCode"]+"' for xml path(''), type) as T(XMLCol) cross apply T.XMLCol.nodes('*') as n(Col) where Col.value('.', 'varchar(1)') = 1 " , con);
try
{
  con.Open();
  cmd.ExecuteNonQuery();
  DataTable dtble = new DataTable();
  SqlDataAdapter dap = new SqlDataAdapter(cmd);
  dap.Fill(dtble);
  if (dtble.Rows.Count > 0)
  {
    result = dtble.Columns.Cast<DataColumn>()
 .Where(c => c.ColumnName != "pcode" && c.ColumnName != "attsno")
 .Where(c => dtble.Rows[0][c].ToString() == "1")
 .Select(c => c.ColumnName)
 .ToList();
    res = result.Count;
    lbl = new Button[res];
    for (i = 0; i < result.Count; i++)
    {

      lbl[i] = new Button();
      lbl[i].Text = result[i];
      lbl[i].ID = "btn" + i.ToString();
      lbl[i].Width = 30;
      //lbl[i].Click += new EventHandler(lbl_click);
      lbl[i].CssClass = "label";
      div1.Controls.Add(lbl[i]);
    }

  }

}
catch
{
  throw;
}
    finally
    {
      if (con != null)
      {
        con.Close();
      }
    }
  } 



  [WebMethod]
  public static string lbl_click()
  {
    return "label1";
  }

希望這會幫助你。

暫無
暫無

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

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