【问题标题】:How to Save All Row values of a gridview at single click in ASP如何在 ASP 中单击保存网格视图的所有行值
【发布时间】:2013-02-14 04:54:54
【问题描述】:

您好,我正在尝试通过单击保存所有 gridview 值。

这是我尝试过的代码。

protected void imgbtnSave_Click(object sender, ImageClickEventArgs e)
{
     // DAL and Other Code here

 foreach (GridViewRow row in gvServicePort.Rows)
    {
      Label _lblOneID = gvServicePort.Rows[row.RowIndex].FindControl("lblOneID") as Label;
        objserRtnDtls.TerminalID = Convert.ToInt16(_lblOneID .Text);

     RadioButton _lblTwo = gvServicePort.Rows[row.RowIndex].FindControl("rdDirectPOL") as RadioButton;   

         if (_lblIsPOL.Checked == true)
            objserRtnDtls.IsPOL = true;
        else
            objserRtnDtls.IsPOL = false;  
         int i = dalSPM.ServicePort_Update(objserRtnDtls, objSerRtn);
}

但是在这里,对于前两次迭代,我得到的返回值是 1,后来是 0,并且它没有保存在 DB 中

【问题讨论】:

  • 尝试先检查是否是数据行:row.RowType==DataControlRowType.DataRow
  • 您能否详细说明该代码
  • 只需将foreach 循环的主体用if(row.RowType==DataControlRowType.DataRow) 包裹起来

标签: asp.net gridview datagridview


【解决方案1】:

一个问题可能是_lblTwo 从未用于填充objserRtnDtls。我假设它可能是 _lblIsPOL。我根据这个假设调整了下面的代码。

我还根据上面的评论包括了对 DataRow 的检查(优秀点 mshsayem)。

protected void imgbtnSave_Click(object sender, ImageClickEventArgs e)
{
    // DAL and Other Code here

    foreach (GridViewRow row in gvServicePort.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            // wire up the controls in this row
            Label _lblOneID = (Label)row.FindControl("lblOneID");
            RadioButton _rdIsPOL = (RadioButton)row.FindControl("rdDirectPOL"); // renamed _lblTwo to _rdIsPOL

            // load the control data into your object
            objserRtnDtls.TerminalID = Convert.ToInt16(_lblOneID.Text);
            objserRtnDtls.IsPOL = _rdIsPOL.Checked; // renamed _lblIsPOL to _rdIsPOL to match the RadioButton above

            // attempt to update the database
            int i = dalSPM.ServicePort_Update(objserRtnDtls, objSerRtn);
        }
    }
}

另一个问题是,您可能需要考虑在每次 foreach 迭代结束时重置 objserRtnDtls,这样您就不会意外地将对象最后一行的旧数据留下。如果您有重复的数据并尝试插入,如果 TerminalID 在您的数据库中应该是唯一的,则它可能会失败。我不知道 objSerRtn 做了什么,所以你必须在那里自己判断。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-25
    • 2013-12-08
    • 2011-12-25
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-10
    相关资源
    最近更新 更多