vs2005中,GridView自带的编辑中的更新按钮不起作用

发布时间:2024-05-22 23:05 发布:上海旅游网

问题描述:

按更新后不会产生异常,就是数据没更新,代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient ;

public partial class _Default : System.Web.UI.Page
{
public SqlConnection GetConnection()
{
string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection myConn = new SqlConnection(myStr);
return myConn;
}
protected void bind()
{
SqlConnection myConn = GetConnection();
myConn.Open();
string sqlStr = "select * from tb_class";
SqlDataAdapter myDa = new SqlDataAdapter(sqlStr, myConn);
DataSet myDs = new DataSet();
myDa.Fill(myDs);
GridView1.DataSource = myDs;
GridView1.DataKeyNames = new string[] { "ClassID" };
GridView1.DataBind();
myDa.Dispose();
myDs.Dispose();
myConn.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
bind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.bind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int ClassID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
string CName = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString();
string sqlStr = "update tb_class set ClassName='" + CName + "'where ClassID='" + ClassID+"'";
SqlConnection myConn = GetConnection();
myConn.Open();
SqlCommand myCmd = new SqlCommand(sqlStr, myConn);
myCmd.ExecuteNonQuery();
myCmd.Dispose();
myConn.Close();
GridView1.EditIndex = -1;
this.bind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
this.bind();
}
}

问题解答:

一般一个页面会在page_load时间中加载一些内容,但是在提交数据到服务器端时会重新加载这些内容,但是这个并不是程序中希望见到的。

在page_load中这样写:
if(!IsPostBack)
{
要加载的内容...
}

表示当第一次加载页面的时候才执行“要加载的内容...”
试试吧

设个断点跟一下就知道了啦~!

热点新闻