问题在于,当我使用button_1从txt文件中读取数据时,我将其放在容器类中。当我想在网站中使用button_2打印容器数据时 - 容器变空。那么问题是如何将数据存储到容器类中?
容器:
public class Matrix
{
public int[,] matrix;
public Matrix()
{
matrix = new int[6, 6];
}
public void AddNumber(int numb, int i, int j)
{
matrix[i, j] = numb;
}
}
网络表单:
public partial class Forma : System.Web.UI.Page
{
Matrix m = new Matrix();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void UploadButton_Click(object sender, EventArgs e)
{
}
protected void Start_Button(object sender, EventArgs e)
{
char[] separators = {' ', '\n', '\r', '\t'};
int numb = 0;
int Counter = 0;
if (!FileUpload1.HasFile)
{
Label1.Text = "Nepasirinkote failo!";
}
else
{
Label1.Text = string.Empty;
StreamReader reader = new StreamReader(FileUpload1.FileContent);
string text = reader.ReadToEnd();
string[] allNumbers = text.Split(separators, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
{
numb = int.Parse(allNumbers[Counter]);
Counter++;
m.AddNumber(numb, i, j);
}
}
Label1.Text = m.matrix[0, 5].ToString();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = m.matrix[0, 5].ToString(); //Container infroamtion dissapears
}
}
答案 0 :(得分:1)
与SmartClient应用程序相反,Web应用程序为每个请求创建页面类的新实例。所以代码
Matrix m = new Matrix();
每当您调用页面或发生回发时都会调用。所以有一个新的矩阵实例,前一个矩阵在第一个请求结束时就消失了。
有一些方法可以在请求之间存储数据,每种方法都有起伏:
此link概述了ASP.NET WebForms中可用的各种状态管理方法。请注意,其中一些是特定于用户的,而其他用户则是共享的。