1

I have written an ASP.NET server control.

View state works perfectly, but when I'm trying to get a value of a control on my custom control with its public instant method, it brings me an exception that there are not control with that ID.

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
TIKSN
  • 615
  • 1
  • 6
  • 24

2 Answers2

1

If you want to get the values from your custom control, you have to register your controls in OnInit event.

//Register your controls
protected override void OnInit(EventArgs e) {
        var controlName = (Type)LoadControl("~/path.ascx");
        controlName.ID = "YOU_MUST_SET_AN_ID";
        placeholder.Controls.Add(controlName);
}


//get your controls (add the following in any method you like)
var controlNameCtrl = (Type)placeholder.FindControl("CONTROLID");
var propertyValue = controlNameCtrl.PropertyName;
profanis
  • 2,741
  • 3
  • 39
  • 49
  • My ID contains of static ("cmbFromDate_") and dynamic (ColumnName) – TIKSN Oct 15 '12 at 09:38
  • I had faced a similar issue and unfortunately this is the only solution I came with. I know that is restrictive to use an ID on Init event, but this will save you for future issues. – profanis Oct 15 '12 at 09:42
0

When you create a custom control, the page that onward identifies the custom control as one entity and you do not get direct access to individual controls in your custom control.

To get the property value of individual elements of custom control, you should define the properties in your custom control which in turn wraps the individual control inside your custom control.

However, you can always get the value of contained control in the user control itself (Not in the page on which it is placed but in the control code itself.). You can also write events in your custom control to make it interact.

Murtuza Kabul
  • 6,438
  • 6
  • 27
  • 34
  • I am using .FindControl(ID) method and it brings me error in this point. – TIKSN Oct 15 '12 at 09:31
  • And another issue is that I have 3 combos on it, and it is possible to have another combos as well. – TIKSN Oct 15 '12 at 09:39
  • sure you can have as many combo as you want. Using FindControl(ID) is not an issue. However it is not very convenient. When you define properties in your user control, you will have to cast it to proper type before you could access the instance properties. Having done so, you would also be able to raise events from the usercontrol. – Murtuza Kabul Oct 15 '12 at 09:42
  • the three combo boxes is date interval kind, from and to value. but there can be multiple of them – TIKSN Oct 15 '12 at 09:44
  • This can work absolutely fine for you. Define a property in your user control named interval. Put the logic in getter which returns you the final interval after calculating the it from the values of all three combo boxes. – Murtuza Kabul Oct 15 '12 at 09:45