我是 stackoverflow 和使用 Microsoft asp.net 开发 Web 应用程序的新手。我使用 MS Visual Studio Professional 2015 作为开发工具。
我想要做的是创建一个简单的网络应用程序用于学习目的。我有三个文件:
我的想法是将多个 aspx 文件使用的所有 Subs 和函数存储在名为 Code.vb 的中央类文件中。在我的 aspx 上,我有一个按钮和一个标签:
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Hello World" OnClick="Button1_Click" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
Button1 的 OnClick 事件从代码隐藏的 WebForm1.aspx.vb 中调用 Button1_Click,它导入中央代码类文件:
Imports WebApplication1.CentralCode.Code
Public Class WebForm1
Inherits System.Web.UI.Page
Public Sub Button1_Click(sender As Object, e As EventArgs)
SetLabelText()
End Sub
End Class
在该类文件中,Sub SetLabelText 应将 Label1 的 Label-text 设置为“一些文本”。
Namespace CentralCode
Public Class Code
Public Shared Sub SetLabelText()
WebApplication1.WebForm1.Label1.Text = "some text"
End Sub
End Class
End Namespace
行WebApplication1.WebForm1.Label1.Text = "some text"是红色下划线的错误消息"WebApplication1.WebForm1.Label1" is "Protected" and not access in this context and "WebForm1" is a class type and can not be used作为表达式
有可能做这样的事情吗?这对我来说会容易得多,因为我的代码可以存储在一个中心位置。
提前谢谢,马库斯
错误消息很明确:您无法从表单 WebForm1 外部访问 Label1。
我建议您将 sub 更改为函数并返回文本:
Public Shared Function GetLabelText() as String
Return "Some Text"
End Function
在 Webform1 中
Public Sub Button1_Click(sender As Object, e As EventArgs)
Label1.Text = GetLabelText()
End Sub
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句