如何用c#对象引用HTML/ASP元素
本文关键字:ASP 元素 HTML 对象引用 何用 | 更新日期: 2023-09-27 18:06:19
我是ASP新手。. NET和c#,我主要使用Java。我想动态地向树视图添加节点。我遵循了一些教程,但每当我实现它们时,它们似乎都不起作用。我不断得到一个错误:"名称'MyTreeView'不存在于当前上下文中"。
下面是c#代码:using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace LocalTest
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MyTreeView.Nodes.Add(new TreeNode("Node1"));
MyTreeView.Nodes[0].ChildNodes.Add(new TreeNode("ChildNode"));
}
}
}
}
而HTML/ASP:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="MyTreeView" Runat="server">
</asp:TreeView>
</div>
</form>
</body>
</html>
"MyTreeView"是包含在Default中的树视图的ID。aspx文件。
我所遵循的几个教程似乎直接使用上面看到的ID访问treeview,这对我来说意义不大。例如,如果我要在Android中这样做,我将不得不使用findViewById并在XML和对象之间建立链接。
有人有什么建议吗?我在这个网站上闲逛了一会儿,我只发现了类似的问题,但我不能得到一个明确的答案。
谢谢。
查看上面的代码,您正在使用所谓的ASP。Net WebForms
,其中有"服务器端"控制(例如<asp:TreeView ID="MyTreeView" Runat="server">
)
"页面"(html aspx)需要以某种方式"连接自己"到代码(c#文件)。它需要一个"服务器端"指令,如下所示:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebFormsApplication.WebForm1" %>
<!DOCTYPE html>
//...the rest of the html goes here plus web controls, etc.
在这一点上,你可以看到像Inherits="WebFormsApplication.WebForm1"
这样的东西映射到Class
:
namespace WebFormsApplication
{
public partial class WebForm1 : System.Web.UI.Page
....
在WebForm1.aspx.cs
文件中,也在指令CodeBehind="WebForm1.aspx.cs"
所以瞧!)
在XML和Object之间建立链接。
Hth…
default.aspx中没有TreeView控件。在。html文件和default.aspx.cs中看不到TreeView控件
您的asp.net页面中似乎缺少Page
指令
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>