Error:当GridView编辑状态获取新值时,往往获取的是修改前的值 问题原因及解决方法...

本文介绍了ASP.NET中处理GridView编辑状态的问题及解决方法。通过调整数据绑定函数的调用位置,确保获取到的是用户更改后的数据。同时给出了具体的代码实现案例。

分析:

如果把数据绑定函数调用直接放在Page_Load()函数里,当GridView编辑状态获取新值时,往往获取的是修改前的值,这是因为页面加载先执行page_load()函数,数据绑定函数就会再次执行,这样GridView里的值就会又变成修改前的值,获取值时就是更改前的值。


解决办法:

把数据绑定函数放在Page_Load()函数的if(!this.page.ispostback)里,这样获取的值就是更改后的值。

获取GridView单元格值办法:

在RowUpdating事件里获取第二个单元格内容

string edit = ((TextBox)(GridView_DetailForEachEquip.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim();

下面解释一下IsPostBack:

//Page.IsPostBack==false表示:第一次访问页面 
//Page.IsPostBack==true表示:用户点击按钮,导致提交表单时产生的页面访问。 
if (!page.ispostback) 
{ 
	BindGrid(); 
} 
public void BindGrid() 
{ 
} 

目的是:

1、避免重复到数据库里提取数据。

2、保持状态。
如果是绑定下拉列表框的话,就必须用这种方式绑定。
在第一次访问的时候绑定下拉列表框,用户可以看到下拉列表框里的选项,然后作选择,比如选择了第三项,然后提交表单,这时我们希望能够得到下拉列表框选定了第三项的状态。

如果不加上 if (!page.ispostback) 的判断的话,那么得到的选项永远都是第一项,因为每次都重新绑定,并且设置第一项被选中。


using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; using DevExpress.XtraEditors; using DevExpress.XtraEditors.Controls; using System.Threading; namespace book_information { public partial class jczl_floor : Form { internal AF AF = new AF(); public menu menu; public jczl_floor(menu fmz) { InitializeComponent(); menu = fmz; } private void floor_Load(object sender, EventArgs e) { selBindw(); init(); } #region 事件区 private void btsel_Click(object sender, EventArgs e) { try { selBindw(); } catch (Exception ec) { MessageBox.Show("错误:" + ec.StackTrace, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } private void btadd_Click(object sender, EventArgs e) { try { jczl_floor_add fma = new jczl_floor_add(this); fma.Text = "增层数"; fma.ShowDialog(); return; } catch (Exception ec) { MessageBox.Show("错误:" + ec.StackTrace, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } private void btexcel_Click(object sender, EventArgs e) { try { this.Invoke(new Action(() => this.Enabled = false)); SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Title = "导出Excel"; saveFileDialog.Filter = "Excel文件(*.xls)|*.xls"; DialogResult dialogResult = saveFileDialog.ShowDialog(this); if (dialogResult == DialogResult.OK) { gridView1.Columns["Operation"].Visible = false; DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions(); gridControl1.ExportToXls(saveFileDialog.FileName); DevExpress.XtraEditors.XtraMessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } this.Invoke(new Action(() => this.Enabled = true)); } catch (Exception ec) { this.Invoke(new Action(() => this.Enabled = true)); MessageBox.Show("错误:" + ec.Message.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } private void btn_Click(object sender, EventArgs e) { try { SimpleButton btn = sender as SimpleButton; if (btn.Name == "btfirst") { txtpageIndex.Text = "1"; } if (btn.Name == "btprevious") { if (Convert.ToInt32(txtpageIndex.Text.Trim()) - 1 > 0) txtpageIndex.Text = (Convert.ToInt32(txtpageIndex.Text.Trim()) - 1).ToString(); else txtpageIndex.Text = "1"; } if (btn.Name == "btnext") { if (Convert.ToInt32(txtpageIndex.Text.Trim()) + 1 <= Convert.ToInt32(lblpages.Text.Trim())) txtpageIndex.Text = (Convert.ToInt32(txtpageIndex.Text.Trim()) + 1).ToString(); } if (btn.Name == "btlast") { txtpageIndex.Text = lblpages.Text.Trim(); } Thread threads; threads = new Thread(selBindw); threads.IsBackground = true; threads.Start(); } catch (Exception ec) { MessageBox.Show("错误:" + ec.Message.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } private void ButtonEdit_ButtonClick(object sender, ButtonPressedEventArgs e) { string sqlcon = AF.sqlcon; int selectedHandle; selectedHandle = this.gridView1.GetSelectedRows()[0]; if (e.Button.Caption == "编辑") { string name, id,status; name = this.gridView1.GetRowCellValue(selectedHandle, "层号").ToString().Trim(); id = this.gridView1.GetRowCellValue(selectedHandle, "编号").ToString().Trim(); status = this.gridView1.GetRowCellValue(selectedHandle, "状态").ToString().Trim(); jczl_floor_edit fmb = new jczl_floor_edit(this); fmb.Text = "信息修改"; fmb.txtname.Text = name; fmb.id.Text = id; fmb.ddlstatus.Text = status; fmb.ShowDialog(); return; } } #endregion #region 函数区 private void init() { ddlpageSize.Properties.Items.Add("10"); ddlpageSize.Properties.Items.Add("20"); ddlpageSize.Properties.Items.Add("50"); ddlpageSize.Properties.Items.Add("80"); ddlpageSize.Properties.Items.Add("100"); ddlpageSize.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor; ddlstatus.Properties.Items.Add("在用"); ddlstatus.Properties.Items.Add("停用"); ddlstatus.Properties.Items.Insert(0, "全部"); ddlstatus.SelectedIndex = 0; ddlstatus.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor; try { this.Invoke(new Action(() => { DevExpress.XtraGrid.Columns.GridColumn NewColumn = this.gridView1.Columns.AddField("Operation"); NewColumn.VisibleIndex = 0; NewColumn.Width = 100; NewColumn.UnboundType = DevExpress.Data.UnboundColumnType.String; NewColumn.Caption = "操作"; NewColumn.OptionsColumn.AllowGroup = DevExpress.Utils.DefaultBoolean.False; DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit buttonEdit = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit(); EditorButton editBtn = new EditorButton(ButtonPredefines.Glyph, "编辑"); editBtn.Appearance.ForeColor = Color.Blue; editBtn.Caption = "编辑"; buttonEdit.Buttons.Add(editBtn); buttonEdit.TextEditStyle = TextEditStyles.HideTextEditor; buttonEdit.ButtonClick += ButtonEdit_ButtonClick; this.gridControl1.RepositoryItems.Add(buttonEdit); NewColumn.ColumnEdit = buttonEdit; buttonEdit.Buttons[0].Visible = false; })); } catch (Exception ec) { MessageBox.Show("错误:" + ec.StackTrace, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } public void selBindw() { this.Invoke(new Action(() => this.Enabled = false)); if (!selBind()) { this.Invoke(new Action(() => this.Enabled = true)); MessageBox.Show("查询错误:连接服务器错误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } this.Invoke(new Action(() => this.Enabled = true)); return; }//统一处理数据查询失败的情况 public bool selBind() { string sqlcon = AF.sqlcon; string pageSize, pageIndex; pageSize = ddlpageSize.Text.Trim(); pageIndex = txtpageIndex.Text.Trim(); string sql = "SELECT*FROM" + "(" + " SELECT TOP(" + pageSize + "*" + pageIndex + ")" + " floorid 编号,floorname 层号,case when status=1 then '在用' else '停用' end 状态,createman 创建人,createtime 创建间,maintenanceman 维护人,maintenancetime 维护间," + " ROW_NUMBER() OVER (ORDER BY xh) rownum,COUNT(1) OVER() AS zcount" + " FROM jczl_floor WITH(NOLOCK) WHERE 1=1"; string str = ""; sql += getWhStr(str); sql += ")temp WHERE temp.rownum>(" + pageSize + "*(" + pageIndex + "-1))"; DataTable dt = new DataTable(); if (!AF.execSql(sql, sqlcon, out dt)) { return false; } if (dt.Rows.Count > 0) getDateRow(Convert.ToInt32(dt.Rows[0]["zcount"].ToString())); else lblpages.Text = "0"; if (dt.Rows.Count == 0 && txtpageIndex.Text != "1") { txtpageIndex.Invoke(new Action(() => txtpageIndex.Text = "1")); selBind(); return true; } int gvRow = gridView1.RowCount; gridControl1.Invoke(new Action(() => gridControl1.DataSource = dt)); if (gvRow == 0)//初始化表格结构 { gridControl1.Invoke(new Action(() => gridView1.Columns[0].Width = 80));//编号 gridControl1.Invoke(new Action(() => gridView1.Columns[1].Width = 100));//层号 gridControl1.Invoke(new Action(() => gridView1.Columns[2].Width = 90));//状态 gridControl1.Invoke(new Action(() => gridView1.Columns[3].Width = 90));//创建人 gridControl1.Invoke(new Action(() => gridView1.Columns[4].Width = 140));//创建间 gridControl1.Invoke(new Action(() => gridView1.Columns[5].Width = 90));//维护人 gridControl1.Invoke(new Action(() => gridView1.Columns[6].Width = 140));//维护间 gridControl1.Invoke(new Action(() => gridView1.Columns[7].Visible = false)); gridControl1.Invoke(new Action(() => gridView1.Columns[8].Visible = false)); gridControl1.Invoke(new Action(() => gridView1.Columns[0].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center)); gridControl1.Invoke(new Action(() => gridView1.Columns[1].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near)); gridControl1.Invoke(new Action(() => gridView1.Columns[2].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center)); gridControl1.Invoke(new Action(() => gridView1.Columns[3].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center)); gridControl1.Invoke(new Action(() => gridView1.Columns[4].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far)); gridControl1.Invoke(new Action(() => gridView1.Columns[5].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center)); gridControl1.Invoke(new Action(() => gridView1.Columns[6].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far)); for (int i = 0; i < gridView1.Columns.Count-1; i++) { gridControl1.Invoke(new Action(() => gridView1.Columns[i].OptionsColumn.AllowEdit = false)); } } return true; } private bool getDateRow(int hshl) { if (Convert.ToInt32(txtpageIndex.Text.Trim()) < 1) { txtpageIndex.Invoke(new Action(() => txtpageIndex.Text = "1")); } if (Math.Ceiling(Convert.ToDouble(hshl) / Convert.ToDouble(ddlpageSize.Text.Trim())) < Convert.ToInt32(txtpageIndex.Text.Trim())) { txtpageIndex.Invoke(new Action(() => txtpageIndex.Text = Math.Ceiling(Convert.ToDouble(hshl) / Convert.ToDouble(ddlpageSize.Text.Trim())).ToString())); selBind(); } lblpages.Invoke(new Action(() => lblpages.Text = Math.Ceiling(Convert.ToDouble(hshl) / Convert.ToDouble(ddlpageSize.Text.Trim())).ToString())); btnpageinfobar.Invoke(new Action(() => btnpageinfobar.Text = "(共" + hshl.ToString().Trim() + "条记录,每页" + ddlpageSize.Text.Trim() + "条,共" + lblpages.Text.Trim() + "页)")); return true; }//调整页码 private string getWhStr(string str) { if (txtname.Text.Trim() != "") { str += "AND floorname LIKE '%" + txtname.Text.Trim() + "%'"; } if (txtid.Text.Trim() != "") { str += "AND floorid LIKE '%" + txtid.Text.Trim() + "%'"; } int isuse; if (ddlstatus.Text.Trim() == "在用") isuse = 1; else isuse = 0; if (ddlstatus.Text.Trim() != "全部" && ddlstatus.Text.Trim() != "") { str += "AND status =" + isuse; } return str; } #endregion } } 用Ajax改写以上代码
最新发布
08-15
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值