Partial Class custom_pager
Inherits System.Web.UI.UserControl
Public Sub Page_Load(ByVal obj As Object, ByVal e As EventArgs) Handles MyBase.Load
Dim lbl As Label = CType(Page.FindControl("msg"), System.Web.UI.WebControls.Label)
lbl.Text = "Raggadaggadooom!"
End Sub
End Class
Jag får nullexeption när jag gör så hära ifrån min user control.
I verkligheten så hade jag tänkt att hämta controllens id med "me.parent.id" men bara som ett test så försökte jag mig på detta.
Hur gör jag?
mmm, jag var tvungen att köra en rekursiv funktion...
Public Overloads Overrides Sub DataBind()
Dim lbl As Label = CType(FindControlByID(Page.Controls, "msg"), Label)
If TypeOf lbl Is Label Then
lbl.Text = "Raggadaggadooom!"
End If
MyBase.DataBind
End Sub
Public Function FindControlByID(ByVal controls As ControlCollection, ByVal id As String) As Control
Dim found As Control = Nothing
For Each control As Control In controls
If control.HasControls Then
found = FindControlByID(control.Controls, id)
If Not (found Is Nothing) Then
' break
End If
End If
If control.ID = id Then
found = control
' break
End If
Next
Return found
End Function
Ok, jag hajjar, bra för en annan gång.
Jag tänkte göra en vanlig UC och använda som templateelement i en grid, men kom på att jag skall göra en iTemlate i stället, vilket är betydligt bättre för mitt ändamål.
public override void DataBind()
{
Label lbl = ((Label)(FindControlByID(Page.Controls, "msg")));
if (lbl is Label) {
lbl.Text = "Raggadaggadooom!";
}
base.DataBind();
}
public Control FindControlByID(ControlCollection controls, string id)
{
Control found = null;
foreach (Control control in controls) {
if (control.HasControls) {
found = FindControlByID(control.Controls, id);
if (!((found == null))) {
}
}
if (control.ID == id) {
found = control;
}
}
return found;
}
Buggrättning
[kod]
public override void DataBind()
{
Label lbl = FindControlByID(Page.Controls, "msg") as Label;
if (lbl!=null) {
lbl.Text = "Raggadaggadooom!";
}
base.DataBind();
}
public Control FindControlByID(ControlCollection controls, string id)
{
Control found = null;
foreach (Control control in controls) {
if (control.ID == id) {
return control;
}
if (control.HasControls()) {
found = FindControlByID(control.Controls, id);
if (found != null) {
return found;
}
}
}
return found;
}
141 ms totalt · 3 externa anrop · v20260731065814-full.25f56b17