How to call functions in a Class file, when inside

2019-08-22 08:06发布

问题:

I'm using a repeater to create an HTML table with values that come from a database. This part is working perfectly:
TEST.ASPX : <td><%# FancyFormat(Eval("MyColumnName"))%></td>

The function I use is defined in my code-behind:
TEST.ASPX.VB : Function FancyFormat(ByVal Whatever As String) As String
It is just a date formatting function, a very generic bit of code.

So then I decide to create a better function in a Class file, within the same project, because I want to use the function on twenty other web pages:
HELPFUL.VB : Public Shared Function BeautifulFormat(ByVal Whatever As String) As String

Blissfully ignorant I type the following:
TEST.ASPX : <td><%# Helpful.BeautifulFormat(Eval("MyColumnName"))%></td>
Sadly I get the error "Helpful is not declared. It may be inaccessible due to its protection level".

I have read the similar question asp.net In a repeater is it possible to call a public function from another class? but those solutions talk about inheritance. It seems inappropriate to abuse inheritance for things like date formatting. Such a function is very 'global' and you'd want to use it in many different places in a project, not just on web pages. What if you needed it in a Web Service, or within GLOBAL.ASAX.VB ?

So my question is: Can you make a function available in the way I want to, without using inheritance? Or do I have to settle for Public Class Helpful Inherits System.Web.UI.Page and change my code-behind files to have Inherits Helpful in them?

回答1:

Do you need to prepend the Project Name then?

<td><%# [ProjectName].Helpful.BeautifulFormat(Eval("MyColumnName"))%></td>

Or add a Namespace reference?

Or just put in a Module and it will be available everywhere.



回答2:

You need to make the Function Public and Shared

Public Shared Function BeautifulFormat(ByVal Whatever As String) As String

End Function