0

I think this question have been asked many times already(I my self asked once),But there is a new problem which i am facing.I am creating an array of buttons onclick of another button in my application.Number of buttons created will depend upon values which i get from database and values which i get from database depends on a session value which i pass in the query.My code is as below..

Code:

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

}

The above method attributes() will be called on a button click,and the session value will also be generated on buttonclick.On research i came to know that the creation of dynamic buttons should be done in page_init event but i cannot do it here.Please help to solve this issue..

2
  • Can you post the lbl_click()....? Commented Apr 1, 2013 at 8:55
  • @Sunil I have updated my question.check it. Commented Apr 1, 2013 at 9:22

2 Answers 2

1

Have a look here.

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

The event is there you just need to wire it up again.

Sign up to request clarification or add additional context in comments.

3 Comments

I did not say you could. Look here instead, maybe a bit more clear:forums.asp.net/t/1589408.aspx/1
I checked that link and someother links too and I know that the dynamic controls should be created or Recreated in preInit event of page life cycle.But i can't do like that for my app.I want to create the controls dynamically in control event of page life cycle.Any ideas?
Sorry but I think you you're missing something because in the links I showed you they do just that. They create the controls in the click event and save the list of buttons in the session object which they iterate thru again in the post back to re-bind the events again.
0

You can achieve this by using jQuery.
Add a jQuery reference to the web page
Get all controls that fit in class ‘label’, on its click event call the server side ‘lbl_click’ method.
Make sure that ‘lbl_click’ method should be marked as static and decorated with [webmethod].

Aspx page

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


Code Behind

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

Hope this will help you.

2 Comments

How to access dynamic array of controls using jquery?
Assign a common css class to all dynamic array of controls (like..'label' in your code). Then access these controls using this class name in jQuery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.