如何在网格视图中更新数据?

时间:2016-05-15 13:51:08

标签: c# asp.net

我尝试在网格视图中更新数据。当我按下网格视图中的编辑按钮时,行数据将填入相关控件中的其他页面并按更新按钮数据将被更新。

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "EditButton")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            GridViewRow row = GridView1.Rows[index];
            Response.Redirect("~/Home.aspx?Id=" + row.Cells[0].Text);
        }    
    }

目标网页代码

public partial class Home : System.Web.UI.Page
{
    Property p = new Property();
    int Id = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        Id = Convert.ToInt32(Request.QueryString["Id"].ToString());
        if (!IsPostBack)
        {
            BindTextBoxvalues();
        }    
    }

    private void BindTextBoxvalues()
    {
        string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        SqlConnection con = new SqlConnection(constr);
        SqlCommand cmd = new SqlCommand("select * from tblUsers where Id=" + Id, con);
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        txtUsername.Text = dt.Rows[0][0].ToString();
        txtEmail.Text = dt.Rows[0][1].ToString();
        txtDob.Text = dt.Rows[0][2].ToString();
        txtPass.Text = dt.Rows[0][3].ToString();

    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        SqlConnection con = new SqlConnection(constr);
        SqlCommand cmd = new SqlCommand("update tblUsers set UserName='" + txtUsername .Text + "',Email='" + txtEmail.Text + "',DOB=" + txtDob.Text + ",Password='" + txtPass.Text + "' where Id=" + Id, con);
        con.Open();
        int result = cmd.ExecuteNonQuery();
        con.Close();
        if (result == 1)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowSuccess", "javascript:alert('Record Updated Successfully');", true);
        }
        Response.Redirect("~/Admin/Home.aspx");   
    }


}

错误:输入字符串的格式不正确。

protected void Page_Load(object sender, EventArgs e)
    {
        Id = Convert.ToInt32(Request.QueryString["Id"].ToString());
        if (!IsPostBack)
      {

0 个答案:

没有答案