天天看點

一個儲存視圖狀态的小例子

using System;

using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        TableMethod();

    }

    private void TableMethod()

    {

        Random random = new Random();

        int rowCount;//行數

        int colCount;//列數

        rowCount = int.Parse(TB_row.Text);

        colCount = int.Parse(TB_col.Text);

        ViewState["rowCount"] = rowCount;

        ViewState["colCount"] = colCount;

        int CurrentRow;//目前行

        int CurrentCol;//目前列

        for (CurrentRow = 1; CurrentRow <= rowCount; CurrentRow++)

        {

            TableRow tableRow = new TableRow();

            Tb_text.Rows.Add(tableRow);//在 Tb_text中添加行

            for (CurrentCol = 1; CurrentCol <= colCount; CurrentCol++)

            {

                TableCell tableCell = new TableCell();

                Image image = new Image();

                image.ImageUrl = string.Format("死神{0}.jpg", random.Next(3) + 1);

                tableCell.Controls.Add(image);

                tableRow.Cells.Add(tableCell);

            }

            this.Tb_text.Rows.Add(tableRow);

        }

    }

    protected void LB_died_SelectedIndexChanged(object sender, EventArgs e)

    {

        if (this.LB_died.SelectedIndex >= 0)

        {

            this.Image_died.ImageUrl = string.Format("死神{0}.jpg", this.LB_died.SelectedIndex + 1);

        }

        if (ViewState["rowCount"] != null)

        {

            this.TB_row.Text = ViewState["rowCount"].ToString();

            this.TB_col.Text = ViewState["colCount"].ToString();

            TableMethod();

        }

    }

}