将行添加到临时GridView

时间:2009-08-26 09:00:37

标签: asp.net gridview

我想要一个ASP.net页面,用户可以在其中向网格视图中添加行(想想在文本框中键入值并单击“添加”以添加到网格视图)。然后单击提交按钮会将所有行保留到数据库中。

对于流量较低的网站,您建议采用哪种合理简单的解决方案来实现这一目标?

1 个答案:

答案 0 :(得分:2)

我已经这样做了几次。我的解决方案的基本前提是您将数据加载到本地集合中,并将其存储在页面的ViewState中。

List<MyObject> lst = new List<MyObject>();

// Populate the list from the database here

// Store this list in the ViewState
ViewState["List"] = lst;

然后我有一个函数将这个列表绑定到GridView,我在第一个Page_Load中调用它,以及修改这个列表的任何函数:

function BindList() {
    List<MyObject> lst = (List<MyObject>) ViewState["List"];
    GridView1.DataSource = lst;
    GridView1.DataBind();
}

添加新项目......

function cmdAdd_Click(object sender, EventArgs e) {
    // Retrieve list from ViewState
    List<MyObject> lst = (List<MyObject>) ViewState["List"];

    // Add the new item
    MyObject newObj = new MyObject();    // Populate this from your form
    lst.Add(newObj);

    // Update the list in the ViewState
    ViewState["List"] = lst;

    // Update the grid to show the new item
    BindList();
}

如果要将所有项目保留到数据库,只需从ViewState中检索列表。

相关问题