Monday, January 19, 2009

Onclick onserverclick htmlbutton problem and solution

Onclick onserverclick htmlbutton problem and solution

While creating controls dynamically in code html button can create a problem.

Example: Consider following code which i was trying to add to Table cell (Created runtime).


Table tblControls = new Table();
TableRow trControl1 = new TableRow();

TableCell tdControl1 = new TableCell();
tdControl1.Text = "<input id='Submit" + i + "' runat='server' type='button' value='Submit' onclick='alert('Yahooooo');' onserverclick='Submit_Click'></input>"

trControl1.Cells.Add(tdControl1);
tblControls.Rows.Add(trControl1);


In above code, onserverclick event was not working for me. Ideally it should work, but after googling, found that other developers are also facing same problem, the alternate work-around i come up with to deal this problem is create HtmlButton runtime its give you more control and flexibility.

List of added feature with solution are:
1. You can pass argument on button click.
2. Invoking Button Click event for specific runtime created control.
3. Better way to deal with client side code and server side code.


HtmlButton htmSubmit = new HtmlButton();
htmSubmit.ID = "Submit" + i.ToString();
htmSubmit.InnerHtml = "Submit";


//Adding client-side event

htmSubmit.Attributes.Add("onclick", "alert('Yahoooooo');");


//For Passing Argument to Button Click Event use Attributes.Add

htmSubmit.Attributes.Add("GuestId", "GuestUserId" + i.ToString());
htmSubmit.Attributes.Add("UserId", "UserId" + i.ToString());
htmSubmit.Attributes.Add("Message", strMessage);
htmSubmit.ServerClick += new System.EventHandler(this.Submit_Click);


//Finally your onseverclick event

protected void Submit_Click(object sender, EventArgs e)
{
HtmlButton btn = (HtmlButton)sender;
string strGuestUserId = btn.Attributes["GuestId"];
string strUserId = btn.Attributes["UserId"];
string strMessage = btn.Attributes["Message"];
Response.Write("Your have clicked " + btn.ID.ToString() + "<br/>" + strGuestUserId + "<br/>" + strUserId + "<br/>" +strMessage);
}

No comments:

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape