0

Here I got a web form I used select Query and displayed it a form and i need it to update using Query I tried lost of method. I couldn't update,it just updating but passing the old value instead of new changed value.

Here is the form 



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Editcar.aspx.cs" MasterPageFile="MasterPage2.master" Inherits ="Editcar" %>
<asp:Content ID="formContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">


 <form id="form1" runat="server" class="col-md-10" methode="post" >


    <asp:Table ID="GridView1" class="nav-justified" runat="server" AutoGenerateColumns="false" Height="628px" Width="763px">
        <asp:TableRow>
           <asp:TableCell>
                <h4> Car name:</h4>

           </asp:TableCell>
           <asp:TableCell>
                <asp:TextBox ID="id" runat="server" name="id" Width="301px" Text='<%# Eval("id") %>' Visible="False" CssClass="form-control"></asp:TextBox>
                <asp:TextBox ID="carmake" runat="server" Font-Names="carmake" Width="301px" Text='<%#  Eval("car_make") %>' CssClass="form-control"></asp:TextBox>

           </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
           <asp:TableCell>
                <h4> Car model:</h4>
           </asp:TableCell>
           <asp:TableCell>
                <asp:TextBox ID="carmodel" runat="server" name="carmodel" Text='<%#  Eval("car_model") %>' Width="301px" CssClass="form-control"></asp:TextBox>
           </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
           <asp:TableCell>
                <h4> Price: </h4>
           </asp:TableCell>
           <asp:TableCell>
                <asp:TextBox ID="price"  name="price" runat="server" Width="301px"  CssClass="form-control"></asp:TextBox>
           </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
           <asp:TableCell>
                <h4> Discounted Price If: </h4>
           </asp:TableCell>
           <asp:TableCell>
                <asp:TextBox ID="d_price" name="d_price" runat="server" Width="301px"  CssClass="form-control"/>
           </asp:TableCell></asp:TableRow><asp:TableRow>
           <asp:TableCell> <h4>Car image (Type url)</h4></asp:TableCell><asp:TableCell>
                <asp:TextBox CssClass="form-control" ID="image"  name="image" runat="server" />Just Location
            </asp:TableCell></asp:TableRow><asp:TableRow>
           <asp:TableCell><h4>Avilability</h4></asp:TableCell><asp:TableCell>
                 <asp:TextBox CssClass="form-control" ID="avail"  name="avail" runat="server" />Just Location
           </asp:TableCell></asp:TableRow><asp:TableRow>
           <asp:TableCell><h4>Quantity</h4></asp:TableCell><asp:TableCell>
                 <asp:TextBox CssClass="form-control" ID="quantity"   name="quantity" runat="server" />Just Location
           </asp:TableCell></asp:TableRow><asp:TableRow>
           <asp:TableCell>
                <h4>Long description </h4>
           </asp:TableCell><asp:TableCell>

                <asp:TextBox ID="details" name="details" runat="server" Width="295px"  CssClass="form-control" Height="81px" TextMode="MultiLine"></asp:TextBox>
           </asp:TableCell></asp:TableRow><asp:TableRow>
           <asp:TableCell>
                <h4>Year </h4>
           </asp:TableCell><asp:TableCell>
                <asp:TextBox ID="year" name="year" runat="server" Width="295px"  CssClass="form-control" ></asp:TextBox>
           </asp:TableCell></asp:TableRow><asp:TableRow>
           <asp:TableCell>
                <h4>Special Discounted(0 0r 1) </h4>
           </asp:TableCell><asp:TableCell>
                <asp:TextBox ID="special" name="special"  runat="server" Width="295px"  CssClass="form-control"  ></asp:TextBox>
           </asp:TableCell></asp:TableRow></asp:Table><asp:Button ID="button" OnClick="button_click" runat="server"  Cssclass="btn btn-primary btn-lg btn-block" Text="Update the car" />

   </form>

HERE is the code fore cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Configuration;
using System.Data;
using MySql.Data.MySqlClient;

public partial class Editcar : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

    using (MySqlConnection con = new MySqlConnection(constr))
    {
        var id = Request.QueryString["id"];
        string selectquery = "SELECT * FROM product WHERE id=" + @id;
        MySqlCommand cmd = new MySqlCommand(selectquery);
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        con.Open();
        cmd.ExecuteNonQuery();

        MySqlDataAdapter da = new MySqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);

        foreach (DataRow dr in dt.Rows)

        {
            newid.Text = dr["id"].ToString();
            carmake.Text = dr["car_make"].ToString();
            carmodel.Text = dr["car_model"].ToString();
            price.Text = dr["unitprice"].ToString();
            d_price.Text = dr["discountprice"].ToString();
            image.Text = dr["image"].ToString();
            quantity.Text = dr["quantity"].ToString();
            avail.Text = dr["availability"].ToString();
            details.Text = dr["details"].ToString();
            year.Text = dr["year"].ToString();
            special.Text = dr["special"].ToString();
        }
    }
}

public void button_click(object sender, EventArgs e)
{
    string constor = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    MySqlConnection conn = new MySqlConnection(constor);

    string sql = "Update product SET car_make=@carmake, car_model=@carmodel, UnitPrice=@price, Discountprice=@d_price, image=@image, Quantity=@quantity, availability=@avail, details=@details, year=@year, special=@special  WHERE id= @id";
    var cmd = new MySqlCommand(sql, conn);

    conn.Open();
    cmd.Parameters.AddWithValue("@id", newid.Text);
    cmd.Parameters.AddWithValue("@carmake", carmake.Text);
    cmd.Parameters.AddWithValue("@carmodel", carmodel.Text);
    cmd.Parameters.AddWithValue("@price", price.Text);
    cmd.Parameters.AddWithValue("@d_price", d_price.Text); // put zero if no discount
    cmd.Parameters.AddWithValue("@image", image.Text);
    cmd.Parameters.AddWithValue("@quantity", quantity.Text);
    cmd.Parameters.AddWithValue("@avail", avail.Text);
    cmd.Parameters.AddWithValue("@details", details.Text);
    cmd.Parameters.AddWithValue("@year", year.Text);
    cmd.Parameters.AddWithValue("@special", special.Text);
    cmd.Parameters.AddWithValue("@id", newid.Text);

    var ex = cmd.ExecuteNonQuery();

    if (ex == 1)
    {
        Response.Redirect("AdminList.aspx");
    }
    else
    {
        Response.Write("Error");
    }
    conn.Close();
}
}

It's Just updating but not getting the table value

I used ajax too it didn't work

3
  • you don't appear to be associating the parameters with the MySQL command object. You declare the parameters and populate them, but they are not associated with the command, so they are not passed to the DB. Try using cmd.Parameters.Add(param[0]); for instance, and repeat for each parameter (or directly declare the new parameter object inside the Add brackets, for brevity). Repeat for all your required parameters. Or even cmd.Parameters.AddWithValue() could save you even more code, then you just specify the name and value and let .NET infer the data type. Commented Apr 3, 2017 at 12:40
  • Those code worked for INSERT, Thank you for your time, Let me try with Commented Apr 3, 2017 at 12:59
  • it should work identically for any statement, select, update, delete, insert - it shouldn't matter. The point is to associate the parameters with the command. Commented Apr 3, 2017 at 13:23

3 Answers 3

1

You are not associating the parameters with the MySQL command object. You declare the parameters and populate them, but they are not associated with the command, so they are not passed to the DB.

You can use either:

cmd.Parameters.Add(param[0]); 

for instance, and repeat for each parameter.

Or use the AddWithValue method for greater brevity:

cmd.Parameters.AddWithValue("@carmake", carmake); 

This just specifies the name and the value, and lets .NET infer the data type. Again, repeat for each parameter. Then you can get rid of the array and all the declarations of new MySqlParameter.

Lastly your SQL string should be like this:

"Update product SET car_make = @carmake, car_model= @carmodel, " //...etc

i.e. not " + @carmake + ", - that's just concatenating the values of your form fields, which happen to have exactly the same names as your SQL parameters.

Sign up to request clarification or add additional context in comments.

19 Comments

That i used but it taking not value instead like '.WebControls.TextBox,' updating to database
"that I tried". Which of the two suggestions did you try? If it's putting "'.WebControls.TextBox" into the database, then there's a good chance that's because the value of the "carkmake" string is "'.WebControls.TextBox". That is not the fault of the SQL parameter. Above in the comments you said my suggestion worked, so I posted it as the answer for future readers. Now you say it doesn't work??
this is the error You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '.WebControls.TextBox, car_model=System.Web.UI.WebControls.TextBox, UnitPrice=Sys' at line 1 instead it like that
Is "button_click" your button event? If so, you can't put all the string values as input parameters to it. The only parameters you can use are "object sender, EventArgs e". Your commented-out version of button_click is more correct in this respect. So then you need to add carmake.Text as the parameter value. And your comment, while helpful, didn't answer either of the questions I asked in my previous comment. Answers to those would still be useful.
for button event i used protected void button_click(object sender, EventArgs e) i'll update the coding above
|
1

Here is the Right method For CS file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Configuration;
using System.Data;
using MySql.Data.MySqlClient;

public partial class Editcar : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

            using (MySqlConnection con = new MySqlConnection(constr))
            {
                var id = Request.QueryString["id"];

                string selectquery = "SELECT * FROM product WHERE id=" + @id;

                MySqlCommand cmmd = new MySqlCommand(selectquery);
                cmmd.Connection = con;
                cmmd.CommandType = CommandType.Text;

                con.Open();
                cmmd.ExecuteNonQuery();

                MySqlDataAdapter da = new MySqlDataAdapter(cmmd);
                DataTable dt = new DataTable();
                da.Fill(dt);

                foreach (DataRow dr in dt.Rows)
                {
                    newid.Text = dr["id"].ToString();
                    carmake.Text = dr["car_make"].ToString();
                    carmodel.Text = dr["car_model"].ToString();
                    price.Text = dr["unitprice"].ToString();
                    d_price.Text = dr["discountprice"].ToString();
                    image.Text = dr["image"].ToString();
                    qnty.Text = dr["quantity"].ToString();
                    avbl.Text = dr["availability"].ToString();
                    details.Text = dr["details"].ToString();
                    year.Text = dr["year"].ToString();
                    special.Text = dr["special"].ToString();
               }
         }
    }
}

public void button_click(object sender, EventArgs e)
{
        string constor = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    MySqlConnection conn = new MySqlConnection(constor);

    string sql = "Update product SET car_make=@carmake, car_model=@carmodel, UnitPrice=@price, Discountprice=@d_price, image=@image, Quantity=@quantity, availability=@avail, details=@details, year=@year, special=@special  WHERE id= @id";

    var cmd = new MySqlCommand(sql, conn);
    conn.Open();
    cmd.Parameters.AddWithValue("@carmake", carmake.Text);
    cmd.Parameters.AddWithValue("@carmodel", carmodel.Text);
    cmd.Parameters.AddWithValue("@price", price.Text);
    cmd.Parameters.AddWithValue("@d_price", d_price.Text); // put zero if no discount
    cmd.Parameters.AddWithValue("@image", image.Text);
    cmd.Parameters.AddWithValue("@quantity", qnty.Text);
    cmd.Parameters.AddWithValue("@avail", avbl.Text);
    cmd.Parameters.AddWithValue("@details", details.Text);
    cmd.Parameters.AddWithValue("@year", year.Text);
    cmd.Parameters.AddWithValue("@special", special.Text);
    cmd.Parameters.AddWithValue("@id", newid.Text);

    var ex = cmd.ExecuteNonQuery();

    if (ex == 1)
    {
        Response.Redirect("AdminList.aspx");
    }
    else
    {
        Response.Write("Error");
    }
    conn.Close();
    }
  }

Here i used if (!this.IsPostBack) so that the conduction prevented Page_load code affect the Button_Click data.

Comments

0

Here is the same method i used for adding(INSERT) from the form

using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;

public partial class Admingroup_Addcar : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    private void ExecuteInsert(string id, string carmake, string carmodel, string price, string d_price, string image,
        string quantity, string details, string year, string special)
    {
        var constr = "SERVER=localhost;" +
                     "DATABASE=carsstore;" +
                     "UID=root;" +
                     "PASSWORD=;";

        var conn = new MySqlConnection(constr);

        var avail = 1;

        var sql =
            "INSERT INTO product (id, car_make, car_model, UnitPrice, Discountprice, image, Quantity, availability, details, year, special) VALUES ('" +
            @id + "','" + @carmake + "','" + @carmodel + "','" + @price + "','" + @d_price + "','" + @image + "','" +
            @quantity + "','" + @avail + "','" + @details + "','" + @year + "','" + @special + "');";

        try
        {
            conn.Open();

            var cmd = new MySqlCommand(sql, conn);
            var param = new MySqlParameter[11];

            param[0] = new MySqlParameter("@id", MySqlDbType.VarChar, 4);
            param[1] = new MySqlParameter("@carmake", MySqlDbType.VarChar, 100);
            param[2] = new MySqlParameter("@carmodel", MySqlDbType.VarChar, 100);
            param[3] = new MySqlParameter("@price", MySqlDbType.VarChar, 100);
            param[4] = new MySqlParameter("@d_price", MySqlDbType.VarChar, 100); // put zero if no discount
            param[5] = new MySqlParameter("@image", MySqlDbType.VarChar, 300);
            param[6] = new MySqlParameter("@quantity", MySqlDbType.VarChar, 300);
            param[7] = new MySqlParameter("@avail", MySqlDbType.VarChar, 2);
            param[8] = new MySqlParameter("@details", MySqlDbType.VarChar, 2000);
            param[9] = new MySqlParameter("@year", MySqlDbType.VarChar, 4);
            param[10] = new MySqlParameter("@special", MySqlDbType.VarChar, 2);

            param[0].Value = id;
            param[1].Value = carmake;
            param[2].Value = carmodel;
            param[3].Value = price;
            param[4].Value = d_price;
            param[5].Value = image;
            param[6].Value = quantity;
            param[7].Value = avail;
            param[8].Value = details;
            param[9].Value = year;
            param[10].Value = special;

            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
        }
        catch (MySqlException ex)
        {
            var msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            conn.Close();
        }
    }

    protected void button_click(object sender, EventArgs e)
    {
        if (price.Text != d_price.Text)
        {
            //call the method to execute insert to the database
            ExecuteInsert(id.Text, carmake.Text,
                carmodel.Text,
                price.Text,
                d_price.Text,
                image.Text,
                quantity.SelectedItem.Text,
                details.Text,
                year.Text,
                special.Text
                );
            Response.Write("Record was successfully added!");
            ClearControls(Page);
        }
        else
        {
            Response.Write("Record Error");
            d_price.Focus();
        }
    }

    public static void ClearControls(Control Parent)
    {
        if (Parent is TextBox)
        {
            (Parent as TextBox).Text = string.Empty;
        }
        else
        {
            foreach (Control c in Parent.Controls)
                ClearControls(c);
        }
    }
} 

1 Comment

It worked we can use the same method but some change in sql Query like var sql ="Update Product SET car_make ='" +@carmake +" like this. But update is throwing error or it not updating

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.