简体   繁体   English

值未在数据库中更新? ASP.NET C#

[英]value not updating in the database ? ASP.NET C#

I have a gridview in which i bound the template field. 我有一个gridview,其中我绑定模板字段。 delete command working fine but update command not working. delete命令工作正常,但update命令无效。 Here is my aspx code: 这是我的aspx代码:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataKeyNames="User_ID" onrowcancelingedit="GridView1_RowCancelingEdit" 
        onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" 
        onrowupdating="GridView1_RowUpdating" style="margin-top: 15px">
        <Columns>
            <asp:TemplateField AccessibleHeaderText="User_ID" HeaderText="User_ID">
                <EditItemTemplate>
                    <asp:TextBox ID="TXT_ID" runat="server" Text='<%# Eval("User_ID") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="txt_id" runat="server" Text='<%# Eval("User_ID") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField AccessibleHeaderText="Name   " HeaderText="Name">
                <EditItemTemplate>
                    <asp:TextBox ID="TXT_NAME" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField AccessibleHeaderText="User_Name" HeaderText="User_Name">
                <EditItemTemplate>
                    <asp:TextBox ID="TXT_USERNAME" runat="server" Text='<%# Eval("User_Name") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="txt_username" runat="server" Text='<%# Eval("User_Name") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField AccessibleHeaderText="Email" HeaderText="Email">
                <EditItemTemplate>
                    <asp:TextBox ID="TXT_EMAIL" runat="server" Text='<%# Eval("Email") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="txt_email" runat="server" Text='<%# Eval("Email") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField AccessibleHeaderText="Password" HeaderText="Password">
                <EditItemTemplate>
                    <asp:TextBox ID="TXT_PASSWORD" runat="server" Text='<%# Eval("Password") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="txt_password" runat="server" Text='<%# Eval("Password") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField AccessibleHeaderText="Date" HeaderText="Date">
                <EditItemTemplate>
                    <asp:TextBox ID="TXT_DATE" runat="server" Text='<%# Eval("Date") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="txt_Date" runat="server" Text='<%# Eval("Date") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:CommandField ShowEditButton="True" />
            <asp:CommandField ShowDeleteButton="True" />
        </Columns>
    </asp:GridView>

here is ASPX.CS code: 这是ASPX.CS代码:

SqlConnection cnn = new SqlConnection("Data Source=LIFE_WELL; Initial catalog=db_compiler; Integrated security=true");
protected void Page_Load(object sender, EventArgs e)
{
    get();   
}
public void get()
{
   SqlCommand cmd = new SqlCommand("SELECT User_ID,Name,User_Name,Email,Password,Date FROM tbl_user", cnn);
    SqlDataAdapter adp = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    adp.Fill(dt);
    cnn.Open();
    cmd.ExecuteNonQuery();
    GridView1.DataSource = dt;
    GridView1.DataBind();
    cnn.Close();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    GridView1.EditIndex = -1;
    get();

}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    Label txtlbl = (Label)GridView1.Rows[e.NewEditIndex].Cells[1].FindControl("txt_id");
     Session["ID"] = txtlbl.Text;
   // Label txtName = (Label)GridView1.Rows[e.NewEditIndex].Cells[1].FindControl("txtName");
    //Label txtUser = (Label)GridView1.Rows[e.NewEditIndex].Cells[1].FindControl("txt_username");
   // Label txtEmail = (Label)GridView1.Rows[e.NewEditIndex].Cells[1].FindControl("txt_email");
   // Label txtpassword = (Label)GridView1.Rows[e.NewEditIndex].Cells[1].FindControl("txt_password");
    GridView1.EditIndex = e.NewEditIndex;
    get();

}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    int id = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
    Delete(id);
    get();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    int id = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
   // TextBox ID = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TXT_ID");
    TextBox Name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TXT_Name");
    TextBox USERNAME = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TXT_USERNAME");
    TextBox EMAIL = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TXT_EMAIL");
    TextBox PASSWORD = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TXT_PASSWORD");
    //TextBox DATE = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TXT_DATE");
    updateTbl(id,Name.Text,USERNAME.Text,EMAIL.Text,PASSWORD.Text);
    GridView1.EditIndex = -1;
    get();
}
public void updateTbl(int id,string name,string username,string email,string pass)
{
    try
    {
        string u= Session["ID"].ToString();
        int i = Int32.Parse(u);
        //String db = Session["value"].ToString();

        //string RNquery = "USE " + db + " EXEC sp_rename '" + oldname + "', '" + newname + "'";
        string updateQuery = "USE db_compiler Update tbl_user SET Name='" + name + "',User_Name='" + username + "',Email='" + email + "',Password='" + pass + "',Confirm_Password='" + pass + "' WHERE User_ID="+ id+"";

        SqlCommand cmd2 = new SqlCommand(updateQuery, cnn);
        // SqlCommand cmd = new SqlCommand(RNquery, cnn);
        cnn.Open();
        cmd2.ExecuteNonQuery();
        //cmd.ExecuteNonQuery();

        cnn.Close();
    }
    catch (SqlException ex)
    {
        Response.Write("<script>alert("+ ex.Message + ")</script>");
    }
}
public void Delete(int id)
{
    string QUERY = "USE db_compiler DELETE FROM tbl_user WHERE User_ID=" + id + "";
    SqlCommand cmd = new SqlCommand(QUERY, cnn);
    cnn.Open();
    cmd.ExecuteNonQuery();
    cnn.Close();
}

No error display.But value not updating.Thanks error值未更新。

在gridview上使用以下属性,它将使您获得新值而不是旧值

Enableviewstate="False"

There might be different reasons of such behaviour and if an unknown issue has occurred in the code where you have a try..catch structure, first what you should do is to get rid of try..catch. 这种行为可能有不同的原因,并且如果您拥有try..catch结构的代码中发生了未知问题,那么首先应该做的就是摆脱try..catch。 For example, your code catches only SqlException and all other exceptions will be ignored. 例如,您的代码仅捕获SqlException,所有其他异常将被忽略。 Even it a SqlException would occur, you output its message with a js script that might fail/ignored/etc. 即使发生SqlException,您也会使用可能失败/忽略/等的js脚本输出其消息。 Remove try..catch and see if it gives any output. 删除try..catch,看看它是否提供任何输出。

If there is still no error will be shown, you should debug the code step by step. 如果仍然没有错误显示,则应逐步调试代码。

Set a breakpoint to updateTbl() and see how your final sql statement will look like. 将一个断点设置为updateTbl()并查看您最终的sql语句的外观。 Copy-paste it to Sql Server Management Studio and try to execute it from there. 将其复制粘贴到Sql Server Management Studio中,然后尝试从那里执行。 It might be that you missed something there. 可能是您错过了那里的东西。 For example, it looks strange that you have a Confirm_Password column in the database. 例如,您在数据库中具有Confirm_Password列看起来很奇怪。 Make sure that all values from all columns got correct values and that id has got an id of edited row (to make sure that you do not update different row and you do not update correct row with old values). 确保所有列中的所有值都具有正确的值,并且该id具有已编辑的行的ID(以确保您不更新其他行并且不使用旧值更新正确的行)。

Other issues in your code: 您代码中的其他问题:

  1. as it was told, your code is vulnerable for sql injections 如前所述,您的代码容易受到sql注入的攻击
  2. there are unused parts that might get debugging complex, eg 有些未使用的零件可能会使调试变得复杂,例如

     Label txtlbl = (Label)GridView1.Rows[e.NewEditIndex].Cells[1].FindControl("txt_id"); Session["ID"] = txtlbl.Text; 

    or 要么

     string u= Session["ID"].ToString(); int i = Int32.Parse(u); 
  3. coding style is sometimes strange, eg 编码风格有时很奇怪,例如

     ..." + id + ""; 
  4. it seems no need to call USE db_compiler in every statement if db is only one and set in ...Initial catalog=db_compiler;... . 如果db仅是一个并且在...Initial catalog=db_compiler;...设置,则似乎无需在每个语句中都调用USE db_compiler Suppose you need to move your application on another server where db will be named differenty - you would need to change all the code because of hardcoded USE db_compiler in it. 假设您需要将应用程序移动到另一台将db命名为别的服务器上-由于其中的USE db_compiler是经过硬编码的,因此您需要更改所有代码。 (The connection string to db must be also moved to web.config). (与db的连接字符串也必须移至web.config)。

you have problem with post back , actually after pressing update button your page do a postback and your changed/edited values are replace by old values , so your record update but with old values so you dont see any change. 您有回发问题,实际上是在按下更新按钮后,您的页面会进行回发,并且您更改/编辑的值将替换为旧值,因此您的记录会更新但具有旧值,因此您看不到任何更改。 use this code in your button click event. 在按钮单击事件中使用此代码。 so that your page dont do any post back. 这样您的页面就不会发回任何邮件。

Response.Redirect(Request.RawUrl);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM