本文介绍了如何将我的类文件编码在单独的文件中以在另一个页面中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I created a code to dynamically create button control, it worked in the .aspx and aspx.cs file, but when I separated the code in a separate class file the project would not compile





我尝试过:



我创建了一个动态创建按钮控件的代码,它在.aspx和aspx.cs文件中工作,但是当我在单独的类文件中分离代码时,项目将无法编译。下面是在页面加载时在aspx和aspx.cs文件中起作用的代码:



Aspx代码:< asp:PlaceHolder ID =PlaceHolder1runat =server >

代码背后:



按钮按钮=新按钮();

button.Text = 测试;

PlaceHolder1.Controls.Add(按钮);



button.Click + = delegate

{

//在这里输入你的代码



};



但是当我在类文件中将它分隔为下面的代码时,它将无法编译但显示错误CS0103:当前上下文中不存在名称'PlaceHolder1'。



使用System;

使用System.Collections.Generic;

使用System.Linq;

使用System.Web;

使用System.Web.UI;

使用System.Data;

使用System.Data.SqlClient;

使用System .Web.UI.WebC ontrols;



命名空间Default.App_Code

{

公共类CreateButtonClass

{



public CreateButtonClass()

{

}

public void CreateTestButton ()

{

按钮按钮=新按钮();

button.Text =测试;

PlaceHolder1.Controls.Add(按钮);



button.Click + = delegate

{

/ /在这里做你的代码



};

}

我的问题是,如何安排代码所以我将编译并调用该方法?



What I have tried:

I created a code to dynamically create button control, it worked in the .aspx and aspx.cs file, but when I separated the code in a separate class file the project would not compile. Below is the code that worked in aspx and aspx.cs file on page load:

Aspx code: <asp:PlaceHolder ID="PlaceHolder1" runat="server">
Code behind:

Button button = new Button();
button.Text = "Test";
PlaceHolder1.Controls.Add(button);

button.Click += delegate
{
//Do your code here

};

But when I separated it in class file as code below, it will not compile but show error that says "CS0103: The name 'PlaceHolder1' does not exist in the current context.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

namespace Default.App_Code
{
public class CreateButtonClass
{

public CreateButtonClass()
{
}
public void CreateTestButton()
{
Button button = new Button();
button.Text = "Test";
PlaceHolder1.Controls.Add(button);

button.Click += delegate
{
//Do your code here

};
}
My question is, how do I arrange the code so that I will compile and call the method?

推荐答案


这篇关于如何将我的类文件编码在单独的文件中以在另一个页面中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 02:59