c# - 如何在视图状态中存储列表以便没有数据丢失以及当我尝试添加新列表时单击添加按钮
问题描述
在“保存”按钮上,仅单击一行正在创建我希望每次单击“保存”按钮时都创建新行。
// 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 请求执行期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
解决方案
推荐阅读
- javascript - 使用 for of 循环时如何将值传递回生成器函数
- java - Java:如何使用 JavaParser 获取 Java 类的标识符数量
- laravel - Laravel 急切加载 SQL?
- java - 从 Java 调用 Python 脚本。我应该使用 Docker 吗?
- performance - Meltdown 缓解与 `calloc()` 的 CoW“延迟分配”相结合是否意味着 calloc() 分配的内存的性能下降?
- php - NumberFormatter 带单数/复数词
- list - 返回直到元素位置之前属于哪个元素的列表
- c++ - 最后推迟标准输出
- php - 获取woocommerce购物车中最高价格的价值
- python - 用于在迭代期间处理集合修改的 Pythonic 设计