【问题标题】:value not updating in the database ? ASP.NET C#值没有在数据库中更新? ASP.NET C#
【发布时间】:2016-07-11 06:48:20
【问题描述】:

我有一个网格视图,我在其中绑定了模板字段。delete 命令工作正常,但update 命令不工作。 这是我的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>

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

没有error 显示。但值没有更新。谢谢

【问题讨论】:

  • 您的代码为 SQLInjection 敞开了大门,尝试参数化查询
  • 你能告诉我我该怎么做吗?
  • 请编辑您的帖子并删除不相关的代码。那么你会打赌更好的答案
  • 我不知道我要删除哪个东西。它只是删除和更新代码。这里没有额外或不相关的代码
  • @Hameed 所以它正在用旧值更新行..这就是为什么你无法看到更改..它的写入值相同

标签: c# asp.net gridview sql-server-2012


【解决方案1】:

在 gridview 上使用以下属性,这将允许您获取新值而不是旧值

Enableviewstate="False"

【讨论】:

  • 非常感谢。现在工作正常..非常感谢。
【解决方案2】:

您在回发时遇到问题,实际上在按下更新按钮后,您的页面会进行回发,并且您更改/编辑的值被旧值替换,因此您的记录更新但使用旧值,因此您看不到任何更改。 在您的按钮单击事件中使用此代码。这样你的页面就不会做任何回帖。

Response.Redirect(Request.RawUrl);

【讨论】:

    【解决方案3】:

    这种行为可能有不同的原因,如果在你有 try..catch 结构的代码中出现未知问题,首先你应该做的是摆脱 try..catch。例如,您的代码仅捕获 SqlException,而所有其他异常都将被忽略。即使会发生 SqlException,您也可以使用可能失败/忽略/等的 js 脚本输出其消息。去掉 try..catch 看看有没有输出。

    如果还是没有报错,请逐步调试代码。

    为 updateTbl() 设置一个断点,看看你最终的 sql 语句会是什么样子。将其复制粘贴到 Sql Server Management Studio 并尝试从那里执行它。可能是你错过了那里的东西。例如,您在数据库中有一个Confirm_Password 列看起来很奇怪。确保所有列中的所有值都具有正确的值,并且 id 具有已编辑行的 id(以确保您不会更新不同的行并且不会使用旧值更新正确的行)。

    代码中的其他问题:

    1. 如前所述,您的代码易受 sql 注入攻击
    2. 有些未使用的部分可能会使调试变得复杂,例如

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

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

      ..." + id + "";
      
    4. 如果db只有一个并且设置在...Initial catalog=db_compiler;...中,似乎不需要在每个语句中调用USE db_compiler。假设您需要将您的应用程序移动到另一台服务器上,其中 db 将被命名为不同 - 您需要更改所有代码,因为其中硬编码了 USE db_compiler。 (到 db 的连接字符串也必须移动到 web.config)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-27
      • 2017-08-03
      • 2016-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多