【问题标题】:Rows added to gridview don't persist when save event is triggered触发保存事件时,添加到 gridview 的行不会持续存在
【发布时间】:2018-06-26 21:57:40
【问题描述】:

我的网页上有一个网格视图,可以动态添加行。有一个 for 循环可以像这样添加行:

protected void AddNewJob(object sender, EventArgs e)
    {
        for(int i = 0; i < Convert.ToInt32(newJobCount.Text);i++)
        {
            TableRow tr = new TableRow();
            tr.Cells.Add(ServicesDDL("-- Select Service Type --"));
            tr.Cells.Add(JobsDDL("-- Select Job Type --"));
            tr.Cells.Add(TextBoxCell());
            tr.Cells.Add(TextBoxCell());
            tr.Cells.Add(TextBoxCell());

            assetTable.Rows.Add(tr);
        }          
    }

在添加行并从其默认值更改行后,循环遍历行并将数据保存到数据库中。当触发页面的保存事件时,我无法让添加到 gridview 的行持续存在并存在于 gridview 上。该代码如下所示:

foreach (TableRow row in assetTable.Rows)
{

if (isFirst)
{
    isFirst = false;
    continue;
}

DropDownList service = (DropDownList)row.Cells[0].Controls[0];
string assetText = service.SelectedItem.Value;
DropDownList jobDescription = (DropDownList)row.Cells[1].Controls[0];
string serialText = jobDescription.SelectedItem.Value;
TextBox equipmentCount = (TextBox)row.Cells[2].Controls[0];
string leaseText = equipmentCount.Text;
TextBox jobSize = (TextBox)row.Cells[3].Controls[0];
string originText = jobSize.Text;
TextBox serialNo = (TextBox)row.Cells[4].Controls[0];
string deliveryText = serialNo.Text;
string oNo = orderNo.Text;

if (assetText != "0" && serialText != "0")
{
    APICallClass.Job j = new APICallClass.Job();
    j.JobTypeID = Convert.ToInt32(serialText);
    j.serviceID = Convert.ToInt32(assetText);
    j.equipment = leaseText;
    j.jobSize = originText;
    j.serialNumbers = deliveryText;
    j.orderID = Convert.ToInt32(global.GlobalID);

    APICallClass.API.AddJob(j, Session["Variable"].ToString());
}
}

当上面粘贴的代码运行时,它只看到从数据库中拉入的行。我认为我的问题可以通过在我不在的某个地方调用 .databind() 之类的东西来解决,但我尝试了几个地方,但他们没有解决问题。

在此先感谢您的帮助,帮助我成为更强大的 ASP.NET 开发人员。

【问题讨论】:

  • 你不能在aspx页面的GridView中添加那些DropDownLists吗?
  • @Win 我不明白你的问题。你能改写一下吗?
  • 我们一般不会在GridView中动态添加控件。它们应该在设计时添加到 aspx 页面内的模板内。

标签: asp.net gridview webforms


【解决方案1】:

当 GridView 为 DataBind()-ed 时,GridView 的内容将根据 GridView 的 DataSource“重建”。如果您需要将新行保留在 GridView 中,则在添加新行后不要调用 DataBind(),或者在将来调用 DataBind() 之前确保新行的内容在 GridView 的 DataSource 中。

在我写过的一个页面中,我曾经遇到过类似的情况并做了后者。初始行的数据在第一次加载页面时从数据库中提取并保存在 ViewState 中。当用户在 GridView 中添加、删除和重新排序行时,页面只是更改了 ViewState 中的数据并重新DataBind()ed GridView。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多