LinkButton in custom Control not rendering ID (or really working at all)
I am guessing this could be related to this but unfortunately the workaround doesn't seem to work in this case.
After struggling with the larger implementation not working, I boiled it down to the simplest case. This does not work.
public class MyButton : Cont开发者_C百科rol
{
public MyButton()
: base()
{
LinkButton but = new LinkButton();
but.CommandName = "test";
but.CommandArgument = "test2";
but.Text = "Click Here";
Controls.Add(but);
}
}
What renders is:
<a href="javascript:__doPostBack('ctl00$ctl11$ctl07','')">Click Here</a>
There are two major problems here. First, there is no ID. It should have tag id='ctl00$ctl11$ctl07'
. So even though it will post, the events never get captured.
Second, it's ignoring the CommandName and CommandArgument, it should be rendering __doPostBackWithOptions
anyway.
Am I being immensely stupid and just overlooking something obvious or is this a huge bug in ASP.NET?
I've done this lots of times before where there were many other controls rendered inside a Control
or WebControl
and never had any problems, so it must have something to do with the simplicity rather than the complexity, I guess.
If anyone can help me solve this it would be much appreciated.
That's because you should implement INamingContainer Interface
Set the ID property of your button.
but.ID = "MyLinkButtonID";
but.Command += new CommandEventHandler(EVENTHANDLER);
If the button is always a member of the class add the button as a member and add it to the Controls collection in the OnInit event.
Forgot to add the event handler for the Command Event.
ARGH! I am kicking myself, the answer is actually a naming container problem. This was one of those situations where all I could do was focus on some detail, which wasn't actually the problem.
My custom control gets emitted by another control... into yet a third control. But there can be several instances of "third control." (The big picture is, I'm making something that will allow me to put a copy of form control buttons both before and after a form. The main control determines which buttons to emit for a given form.).
So the "third control" was not a naming container. And that was killing it. But I never got any errors about ID conflicts, it just didn't work.
精彩评论