November 30, 2011

Dynamically Create Link Button and Add Command event

Below is the code which you can write to create Dynmic Link Button in C#


    LinkButton  hl = new LinkButton ();
                        hl.Text = "Delete Check";
                        String D = ds.Tables[0].Rows[i]["Date"].ToString();
                     //   hl.Click += new EventHandler(this.MyButtonHandler);
                        hl.Command += new CommandEventHandler(this.MyButtonHandler);
                        hl.CommandArgument = ds.Tables[0].Rows[i]["ID"].ToString();
                        hl.ID = "DeleteLink" + i.ToString();


                        div3.Controls.Add(hl);
                        div3.Controls.Add(new LiteralControl("<br/>"));


                        ViewState["DataSet"] = ds;




                    }
                    ViewState["recordsCount"] = ds.Tables[0].Rows.Count.ToString();


                }


//Event Handler which executes on Click on the Link Button



 void MyButtonHandler(object sender, CommandEventArgs e)
        {
            string  ID = e.CommandArgument.ToString();
             //Business Logic Comes Here
            }


       }


This Code works perfect when you are creating dynamic Link Buttons On page Load.


But In My case I wanted these links to be created on Some Search Button Click .
and When I was clicking on the Link Button I saw that Event Handler code is not executing because you have to add them on Page_Load when you are dynamically creating them , but here I got the Hack of it .


You recreate the Same Hyperlink in PageLoad also on post back with same "ID"(Link Button ID)
So then I wrote below code on the page load , and it worked well.







protected void Page_Load(object sender, EventArgs e)
    {
               if (IsPostBack)
                {
                    if (ViewState["recordsCount"] != null)
                    {
                        for (int i = 0; i < int.Parse(ViewState["recordsCount"].ToString()); i++)
                        {


                            LinkButton hl = new LinkButton();
                            hl.ID = "DeleteLink" + i.ToString();
                            div3.Controls.Add(hl);
                            hl.Command += new CommandEventHandler(this.MyButtonHandler);
                            DataSet ds1 = (DataSet)ViewState["DataSet"];
                            hl.CommandArgument = ds1.Tables[0].Rows[i]["ID"].ToString();
                               
                        }
                    }
                }




The reason of using ViewState here is my command argument for each link was a cell of a DataSet which I was binding from Data Base . So I saved that DataSet in the view State to make it accessible on PostBack in Page Load

No comments:

Post a Comment