0

我有一个网格视图。

我正在尝试编辑它,但价值没有得到更新。

我的代码:

 protected void Page_Load(object sender, EventArgs e)
        {

            con = new SqlConnection("Data Source=192.168.51.71;Initial Catalog=WebBasedNewSoft;User ID=sa;password=prabhu");

            BindGrid();
        }
        private void BindGrid()
        {
            try
            {
                da = new SqlDataAdapter("select * from emp", con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                GridView1.DataSource = ds.Tables[0];
                GridView1.DataBind();
            }
            catch (Exception ex)
            {
            }
        }
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int index = GridView1.EditIndex;

            GridViewRow row = GridView1.Rows[index];

            string eName = ((TextBox)row.Cells[2].Controls[0]).Text.ToString().Trim();

            try
            {
                con.Open();
                cmd = new SqlCommand("update emp set empName='" + eName + "'", con);
                cmd.ExecuteNonQuery();
                con.Close();
                BindGrid();
                GridView1.EditIndex = -1;
            }
            catch (Exception ex)
            {
            }
            finally
            {

            }

        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            BindGrid();
        }
    }

请让我知道我犯错的地方。

4

2 回答 2

3

BindGrid()在事件中使用Page.IsPostBack如下Page_Load

if(!Page.IsPostBack)
{
     BindGrid();
}

编辑 1

我认为以下行应该有效

   BindGrid();
   GridView1.EditIndex = -1;

由于它不起作用,请查看 catch 块中是否有任何错误。

  catch (Exception ex)
  {
       Response.Write(ex.Message);
  }

看看天气有没有错误?

于 2013-07-05T05:42:15.200 回答
2

您可以尝试这样...因为...当您单击编辑按钮时,您的页面加载事件首先被调用....在页面加载时您再次绑定gridview ...因此它的编辑索引丢失,因为它再次绑定。 ..它每次都将编辑索引设置为-1 ...

 protected void Page_Load(object sender, EventArgs e)
        {
        if(!Page.IsPostBack)
              {
             con = new SqlConnection("Data Source=192.168.51.71;Initial            Catalog=WebBasedNewSoft;User ID=sa;password=prabhu");

            BindGrid();
        }
}

Edit1 : OP After Update Edit Mode doesn't go.. 您必须在其绑定之前设置 gridview 编辑索引,如下所示....

try
            {
                con.Open();
                cmd = new SqlCommand("update emp set empName='" + eName + "'", con);
                cmd.ExecuteNonQuery();
                con.Close();
                GridView1.EditIndex = -1;//Put this line Before the Binding of GridView
                BindGrid();

            }
于 2013-07-05T05:41:42.137 回答