C# LinkButton created dynamically problem

55 Views Asked by At

I've created in my code a linkButton dynamically using this:

LinkButton linkPDFQ = new LinkButton();
linkPDFQ.ID = "linkPDF";
linkPDFQ.CommandArgument = fisrtArg + ";" + secondArg;
linkPDFQ.Text = fisrtArg;
linkPDFQ.Command += new CommandEventHandler(PDFCLink_Action);
row.Cells[0].Controls.Add(linkPDFQ);

where row is coming from a GridViewRow and the CommandEventHandler is this

protected void PDFCLink_Action(object sender, CommandEventArgs e)
{
   string[] arg = new string[2];
   arg = e.CommandArgument.ToString().Split(';');

   string arg1 = arg[1];
   string arg2 = arg[2];
   Response.Write("<script>alert('" + arg1 + arg2 "'); </script>");
}

only to see if I click on linkButtton then I receive the alert... but nothing!!! The linkButton doesn't work... I have made another linkButton starting from aspx with a similar code and everything goes well because in apsx I can use the method OnCommand that it's not possible to use in aspx.cs. What I miss or where I made an error? How is possible to replace OnCommand in cs file? Thanks

2

There are 2 best solutions below

0
Swinkaran On

The code below is working fine. I found couple of errors in the code and fixed, Please see the below comments.

protected void Page_Load(object sender, EventArgs e)
{
    // some dummy values
    var fisrtArg = "First arg 1";
    var secondArg = "SEcond arg 2";

    LinkButton linkPDFQ = new LinkButton();
    linkPDFQ.ID = "linkPDF";
    linkPDFQ.CommandArgument = fisrtArg + ";" + secondArg;
    linkPDFQ.Text = fisrtArg;
    linkPDFQ.Command += new CommandEventHandler(PDFCLink_Action);

    // Temporarily adding to the panel - But you can add it to your row cell
    Panel11.Controls.Add(linkPDFQ);
}

protected void PDFCLink_Action(object sender, CommandEventArgs e)
{
    string[] arg = new string[2];
    arg = e.CommandArgument.ToString().Split(';');

    // I found errors in arg indexes.
    //string arg1 = arg[1]; This should be arg[0]
    //string arg2 = arg[2]; This should be arg[1]

    // You are missing a '+'  next to the arg2
    //Response.Write("<script>alert('" + arg1 + arg2 "'); </script>");

    // working code
    string arg1 = arg[0];
    string arg2 = arg[1];
    Response.Write("<script>alert('" + arg1 + arg2 + "'); </script>");
}

Other than above, the CommandEventHandler you implemented is correct. Please let me know if it works.

0
Sujit.Warrier On

Just a warning. dynamically created controls are a bad idea. they get destroyed and recreated in each postback. So when you click the event gets triggered and postback happens, this causes the dynamic button to be destroyed and recreated. When this happens whatever happened in your event handler is ignored as the original button which triggered the event has been destroyed.