Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function in User Control from code behind of the page

Now this is all way simplified, but here goes:

I have a User Control that consists only of a single *.ascx file. The control has no code-behind: it's just a script with a few functions, like this:

<%@ Control Language="VB" EnableViewState="False" ClassName="MyControlType" %>
<script runat="server">
    Public Function MyFunction() As String
       return "CalledMyFunction!"
    End Function
</script>

That's the entire file. I can successfully add this control to an aspx page using markup like so:

<%@ Register Src="~/path/to/Control.ascx" TagPrefix="aaa" TagName="MyControl" %>
...
<aaa:MyControl runat="server" id="MyControl1" />

Now what I want to do is call MyFunction from the page's code-behind, like this:

Dim someString As String = MyControl1.MyFunction()

Unfortunately, I can't do that. Instead, I get a compile error to the effect of "'MyFunction' is not a member of 'System.Web.UI.UserControl'."

I've also tried this:

Dim someString As String = DirectCast(MyControl1, MyControlType).MyFunction()

and then the compiler tells me, "Type 'MyControlType' is not defined."

I've played with this a lot, and I just can't make it work. All efforts to cast MyControl1 to a more exact type have failed, as have other work-arounds. I suspect the problem is that the ascx file without a code-behind is unable to be compiled to an assembly but the code-behind wants to be compiled to an assembly and therefore the compiler gets confused about what type the control is.

What do I need to do to be able to call that function?

[edit]
So I'm just gonna have to add code-behind for the user control. It's what I wanted to do anyway. I'd still like to know how to do this without needing one, though.

like image 260
Joel Coehoorn Avatar asked Nov 15 '22 16:11

Joel Coehoorn


1 Answers

Weird works for me.

Imports Microsoft.VisualBasic

Public Class MyControlType
    Inherits UserControl
End Class

.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<%@ Register Src="~/WebUserControl.ascx" TagPrefix="aaa" TagName="MyControl"  %>
...
<aaa:MyControl runat="server" id="MyControl1"  />

.

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
        Dim someString As String = MyControl1.MyFunction()
    End Sub

End Class

.

<%@ Control Language="VB" EnableViewState="False"  %>
<script runat="server">
    Public Function MyFunction() As String
       return "CalledMyFunction!"
    End Function
</script>
like image 168
BigJump Avatar answered Jan 18 '23 02:01

BigJump