网格未按编辑按钮按下更新

时间:2013-07-05 05:40:09

标签: c# asp.net .net visual-studio-2010

我有一个gridview。

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

我的代码:

 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();
        }
    }

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

2 个答案:

答案 0 :(得分:3)

BindGrid()事件

中使用Page.IsPostBack内的Page_Load,如下所示
if(!Page.IsPostBack)
{
     BindGrid();
}

编辑1

我认为以下行应该有效

   BindGrid();
   GridView1.EditIndex = -1;

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

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

看天气有没有错误?

答案 1 :(得分:2)

您可以尝试这样...因为当您单击编辑按钮时,您的pageload事件首先被调用....而在页面加载时,您再次绑定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编辑模式不会... 您必须在其绑定之前设置gridview Edit索引,如下所示....

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();

            }