首页 > 解决方案 > 如何在视图状态中存储列表以便没有数据丢失以及当我尝试添加新列表时单击添加按钮

问题描述

在“保存”按钮上,仅单击一行正在创建我希望每次单击“保存”按钮时都创建新行。

// game = (List)(ViewState["newGame"]); 我试过这样但显示错误请帮助我。

protected void Page_Load(object sender, EventArgs e) {

        if (!IsPostBack)
            BindGridList();

    }
    protected List<Game> GetGameList()
    {
        List<Game> game = new List<Game>();
        Game lstGames = new Game("Counter Strike", "FPS", "20");

        game.Add(lstGames);
        lstGames = new Game("Fifa 19", "TPP", "50");
        game.Add(lstGames);
        lstGames = new Game("GTA V", "TPP", "45");
        game.Add(lstGames);
        lstGames = new Game("Apex Legends", "TPP", "20");
        game.Add(lstGames);
        lstGames = new Game("Jurrasic World", "3D", "100");
        game.Add(lstGames);
        lstGames = new Game("Tressure Hunt", "3D", "100");
        game.Add(lstGames);
        lstGames = new Game("X Man Origin", "TPP", "100");
        game.Add(lstGames);

       // ViewState["newGame"] = game;

        return game;

    }

    protected void BindGridList()
    {

        PriceList.DataSource = GetGameList();
        PriceList.DataBind();
    }


    protected void OnAddClick(object sender, EventArgs e)
    {
        txtGameName.Visible = true;
        txtGameCategory.Visible = true;
        txtGamePrice.Visible = true;
        btnSave.Visible = true;
        Update.Visible = true;
        btnUpdate.Visible = false;

    }

    protected void OnSaveClick(object sender, EventArgs e)
    {

        txtGameName.Visible = false;
        txtGameCategory.Visible = false;
        txtGamePrice.Visible = false;
        btnUpdate.Visible = false;
        Update.Visible = false;
        btnSave.Visible = false;

        string txtName = txtGameName.Text;
        string txtCategory = txtGameCategory.Text;
        string txtPrice = txtGamePrice.Text;

        List<Game> game = new List<Game>();

       // game = (List<Game>)(ViewState["newGame"]);
        game = GetGameList();
       // ViewState["newGame"] = game;

        Game lstNewGame = new Game(txtName, txtCategory, txtPrice);
        game.Add(lstNewGame);

        PriceList.DataSource = game;
        PriceList.DataBind();


    }
}
public class Game
{
    public string Name { get; set; }
    public string Category { get; set; }
    public string Price { get; set; }
    public Game(string name, string category, string price)
    {
        this.Name = name;
        this.Category = category;
        this.Price = price;
    }
}

}

当前 Web 请求执行期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

标签: c#asp.net

解决方案


推荐阅读