更新不适用于更新网格视图事件

时间:2012-07-08 14:15:55

标签: asp.net sql-server-2008-r2

我在sql server中测试我的查询,它正在100%工作 但在我的页面不工作! 这是我的查询

UPDATE Employee SET 
       Name='jojo',
       Age=19,
       GenderID=2,
       CountryID=5,
       Mobile=0917021092 
WHERE EmployeeID=10

这是我的代码

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {            
            string s = GridView1.DataKeys[e.RowIndex].Value.ToString();

            Label id = (Label)GridView1.Rows[e.RowIndex].FindControl("lblEditID");   
            Label EmployeeID = (Label)GridView1.Rows[e.RowIndex].FindControl("lblEmployeeID");
            TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditName");
            TextBox age = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditAge");
            DropDownList gender = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropGender");
            DropDownList country = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropCountry");
            TextBox mobile = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditMobile");

            string stringconnectiong = ConfigurationManager.ConnectionStrings["Employee_TestConnectionString"].ConnectionString;
            string sql = "update Employee set Name=@Name, Age=@Age,GenderID=@GenderID , CountryID=@CountryID , Mobile=@Mobile where EmployeeID=@EmployeeID  AND ID=@ID";

            SqlConnection con = new SqlConnection(stringconnectiong);

          try
          {
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Parameters.AddWithValue("@EmployeeID", EmployeeID.Text);
            cmd.Parameters.AddWithValue("@ID", id.Text);
            cmd.Parameters.AddWithValue("@Name", name.Text);
            cmd.Parameters.AddWithValue("@Age", age.Text);
            cmd.Parameters.AddWithValue("@GenderID", gender.SelectedValue);
            cmd.Parameters.AddWithValue("@CountryID", country.SelectedValue);
            cmd.Parameters.AddWithValue("@Mobile", mobile.Text);
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = sql;
            cmd.Connection = con;
            cmd.ExecuteNonQuery();
            SqlDataAdapter dr = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            dr.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.EditIndex = -1;
            BindGridview();

        }

        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Error Updating ";
            msg += ex.Message;
            throw new Exception(msg);
        }

        finally
        {
            con.Close();
            con.Dispose();
            BindGridview();
        }

    }

1 个答案:

答案 0 :(得分:0)

由于您的数据源是数据集,因此您需要通过DataMember属性指定您正在使用的数据集中的数据表。或者只使用数据表作为数据源。

使用以下内容替换数据集行:

DataTable dt = new DataTable();
dr.Fill(dt);
GridView1.DataSource = dt;

此外,请使用GridView1_RowUpdated事件。在更新表之前,GridView1_RowUpdating事件被触发,因此您的参数值尚未更新。