简体   繁体   中英

How to update profile in ASP.NET with SQL Server database using C#

I looked through some code for updating profile details that uses an Access database. However, for my current program, I'm currently using a SQL Server database.

As such, I'm trying to adjust these codes to make it work for the SQL Server database.

The objective of the button programmed is to allow the program to update the user profile details of the user that have logged in.

However, I'm unable to do so as upon clicking of the button, I wasn't able to input information in the database.

The exception being thrown:

Error 15 Argument missing LINE 41 

Here's my code-behind file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class RealClientEditProfileaspx : System.Web.UI.Page

{
    public string UFlag = "F"; public string strUserId;
    static readonly string scriptSuccessUpdate = "<script language =\"javascript\">\n" +
      "alert (\"Update Successful - Please surf to other pages to shop\");\n </script>";
    protected void Page_Load(object sender, EventArgs e)
    {
        firstnameLabel.Text = Session["cFirstName"].ToString();
        lastnameLabel.Text = Session["cLastName"].ToString();
        dobLabel.Text = Session["cDOB"].ToString();
        companyLabel.Text = Session["cCompanyName"].ToString();
        addressLabel.Text = Session["cAddress"].ToString();
        zipcodeLabel.Text = Session["cZipCode"].ToString();
        phonenumberLabel.Text = Session["cPhoneNo"].ToString();
        faxnumberLabel.Text = Session["cfax"].ToString();
        emailLabel.Text = Session["cEmail"].ToString();
        passwordLabel.Text = Session["cPassword"].ToString();
        foreach (char ch in passwordLabel.Text.ToCharArray())
        {
            realPasswordLabel.Text += "*";
        }
    }

    public void UpdateCustomer(string strFName, string strFValue)
    {
        SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Desktop\TemporarySter\App_Data\legitdatabase.mdf;Integrated Security=True;Connect Timeout=30;MultipleActiveResultSets=true");
        conn.Open();
        Type csType = this.GetType();
        SqlCommand com;
        SqlDataReader rdr;
        String strSQL = "UPDATE Client SET " + strFName + " = @newValue WHERE ClientNo = @ClientNo ";
        com = new SqlCommand(strSQL, conn);
        com.Parameters.Add("@newValue", ).Value = strFValue;
        com.ExecuteNonQuery();
        UFlag = "T";
        conn.Close();

        string insertQuery = "UPDATE Client (cFirstName, cLastName, cDOB, cCompanyName, cAddress, cZipCode, cPhoneNo, cFax, cEmail, cUsername, cPassword) values (@firstname,@lastname,@dob,@companyname,@address,@zipcode,@phoneno,@fax,@email,@password)";
        com = new SqlCommand(insertQuery, conn);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
       strUserId = (string)Session["sUserId"];

        if (firstnameTB.Text != "")
        {
            String strFName = "cFirstName"; String strFValue = firstnameTB.Text;
            UpdateCustomer(strFName, strFValue);

        }

        if (lastnameTB.Text != "")
        {
            String strFName = "cLastName"; String strFValue = lastnameTB.Text;
            UpdateCustomer(strFName, strFValue);
        }

        if (dobTB.Text != "")
        {
            String strFName = "cDOB"; String strFValue = dobTB.Text;
            UpdateCustomer(strFName, strFValue);
        }

        if (addressTB.Text != "")
        {
            String strFName = "cAddress"; String strFValue = addressTB.Text;
            UpdateCustomer(strFName, strFValue);
        }

        if (zipcodeTB.Text != "")
        {
            String strFName = "cZipCode"; String strFValue = zipcodeTB.Text;
            UpdateCustomer(strFName, strFValue);
        }

        if (phonenumberTB.Text != "")
        {
            String strFName = "cPhoneNo"; String strFValue = phonenumberTB.Text;
            UpdateCustomer(strFName, strFValue);
        }

        if (faxnumberTB.Text != "")
        {
            String strFName = "cFax"; String strFValue = faxnumberTB.Text;
            UpdateCustomer(strFName, strFValue);
        }

        if (emailTB.Text != "")
        {
            String strFName = "cEmail"; String strFValue = emailTB.Text;
            UpdateCustomer(strFName, strFValue);
        }

        if (passwordTB.Text != "")
        {
            String strFName = "cPassword"; String strFValue = passwordTB.Text;
            UpdateCustomer(strFName, strFValue);
        }

        if (UFlag == "T")
        {
            Type strType = this.GetType();
            ClientScript.RegisterStartupScript(strType, "Success", scriptSuccessUpdate);
        }
    }
}

and here's the ASPX markup:

<%@ Page Title="" Language="C#" MasterPageFile="~/ClientPortal.master" AutoEventWireup="true" CodeFile="RealClientEditProfileaspx.aspx.cs" Inherits="RealClientEditProfileaspx" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    <style type="text/css">

        .style1
        {
            font-size: 1em;
        }
        .style4
        {
            width: 208px;
        }
        .style8
        {
            color: #FF9933;
        }
        .auto-style8 {
            width: 121px;
            text-align: right;
        }
        .auto-style9 {
            width: 227px;
            text-align: left;
        }
        .auto-style10 {
            text-align: left;
        }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <br />
    <table class="auto-style2">
        <tr>
            <td class="auto-style8">
                <asp:Label ID="Label1" runat="server" Text="Particulars"></asp:Label>
            </td>
            <td class="auto-style9">&nbsp;
                <asp:Label ID="Label12" runat="server" style="text-align: left" Text="Current particulars"></asp:Label>
            </td>
            <td class="auto-style10">
                <asp:Label ID="Label23" runat="server" Text="Updated particulars"></asp:Label>
            </td>
        </tr>
        <tr>
            <td class="auto-style8">First Name:</td>
            <td class="auto-style9">&nbsp;
                <asp:Label ID="firstnameLabel" runat="server" Text="Label"></asp:Label>
            </td>
            <td class="auto-style10">
                <asp:TextBox ID="firstnameTB" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="auto-style8">
                <asp:Label ID="Label3" runat="server" Text="Last Name:"></asp:Label>
            </td>
            <td class="auto-style9">&nbsp;
                <asp:Label ID="lastnameLabel" runat="server" Text="Label"></asp:Label>
            </td>
            <td class="auto-style10">
                <asp:TextBox ID="lastnameTB" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="auto-style8">
                <asp:Label ID="Label4" runat="server" Text="Date Of Birth:"></asp:Label>
            </td>
            <td class="auto-style9">&nbsp;
                <asp:Label ID="dobLabel" runat="server" Text="Label"></asp:Label>
            </td>
            <td class="auto-style10">
                <asp:TextBox ID="dobTB" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="auto-style8">
                <asp:Label ID="Label5" runat="server" Text="Company Name:"></asp:Label>
            </td>
            <td class="auto-style9">&nbsp;
                <asp:Label ID="companyLabel" runat="server" Text="Label"></asp:Label>
            </td>
            <td class="auto-style10">
                <asp:TextBox ID="companyTB" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="auto-style8">
                <asp:Label ID="Label6" runat="server" Text="Address:"></asp:Label>
            </td>
            <td class="auto-style9">&nbsp;
                <asp:Label ID="addressLabel" runat="server" Text="Label"></asp:Label>
            </td>
            <td class="auto-style10">
                <asp:TextBox ID="addressTB" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="auto-style8">
                <asp:Label ID="Label7" runat="server" Text="Zip Code:"></asp:Label>
            </td>
            <td class="auto-style9">&nbsp;
                <asp:Label ID="zipcodeLabel" runat="server" Text="Label"></asp:Label>
            </td>
            <td class="auto-style10">
                <asp:TextBox ID="zipcodeTB" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="auto-style8">
                <asp:Label ID="Label8" runat="server" Text="Phone Number:"></asp:Label>
            </td>
            <td class="auto-style9">&nbsp;
                <asp:Label ID="phonenumberLabel" runat="server" Text="Label"></asp:Label>
            </td>
            <td class="auto-style10">
                <asp:TextBox ID="phonenumberTB" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="auto-style8">
                <asp:Label ID="Label9" runat="server" Text="Fax Number:"></asp:Label>
            </td>
            <td class="auto-style9">&nbsp;
                <asp:Label ID="faxnumberLabel" runat="server" Text="Label"></asp:Label>
            </td>
            <td class="auto-style10">
                <asp:TextBox ID="faxnumberTB" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="auto-style8">
                <asp:Label ID="Label10" runat="server" Text="Email:"></asp:Label>
            </td>
            <td class="auto-style9">&nbsp;
                <asp:Label ID="emailLabel" runat="server" Text="Label"></asp:Label>
            </td>
            <td class="auto-style10">
                <asp:TextBox ID="emailTB" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="auto-style8">
                <asp:Label ID="Label11" runat="server" Text="Password:"></asp:Label>
            </td>
            <td class="auto-style9">&nbsp;
                <asp:Label ID="realPasswordLabel" runat="server" Text="********"></asp:Label>
            </td>
            <td class="auto-style10">
                <asp:TextBox ID="passwordTB" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="auto-style8">&nbsp;</td>
            <td class="auto-style9">
                <asp:TextBox ID="passwordLabel" runat="server" ReadOnly="True" TextMode="Password" Visible="False"></asp:TextBox>
            </td>
            <td class="auto-style10">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" style="text-align: right" Text="Update" />
            </td>
        </tr>
    </table>
</asp:Content>

The actual fix:

You must supply a value for the @CustomerNo parameter. In the Button1_Click method, you have a variable called strUserId , which should be passed into UpdateCustomer() :

UpdateCustomer(strUserId, strFName, strFValue);

Then in UpdateCustomer :

public void UpdateCustomer(string strUserId, string strFName, string strFValue)
{
    ...

    com.Parameters.Add("@ClientNo", ).Value = strUserId;
    com.Parameters.Add("@newValue", ).Value = strFValue;

Then remove the INSERT logic, since this doesn't belong in a method for "updating customers".

Suggested improvements

Really, this could use a little object oriented goodness. I would create a class in C# to represent a customer:

public class User
{
    public long Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string CompanyName { get; set; }
    public string Address { get; set; }
    public string ZipCode { get; set; }
    public string PhoneNumber { get; set; }
    public string FaxNumber { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}

This represents your Domain Model. Next, you want to use it in your UserControl.

First, the Button1_Click method turns into:

protected void Button1_Click(object sender, EventArgs e)
{
    User customer = new User()
    {
        Id = long.Parse((string)Session["sUserId"]),
        FirstName = firstnameTB.Text.Trim(),
        LastName = lastnameTB.Text.Trim(),
        DateOfBirth = DateTime.Parse(dobTB.Text.Trim()),
        Address = addressTB.Text.Trim(),
        ZipCode = zipcodeTB.Text.Trim(),
        PhoneNumber = phonenumberTB.Text.Trim(),
        FaxNumber = faxnumberTB.Text.Trim(),
        Email = emailTB.Text.Trim(),
        Password = passwordTB.Text.Trim()
    };

    UpdateCustomer(customer);

    if (UFlag == "T")
    {
        Type strType = this.GetType();
        ClientScript.RegisterStartupScript(strType, "Success", scriptSuccessUpdate);
    }
}

This is much cleaner to read and easier to maintain. The call to UpdateCustomer indeed only updates a customer. Now let's look at changes to the UpdateCustomer method:

public void UpdateCustomer(User customer)
{
    string updateSql =
    @"UPDATE Client
    SET cFirstName = @FirstName,
        cLastName  = @LastName,
        cDOB       = @DateOfBirth,
        cAddress   = @Address,
        cZipCode   = @ZipCode,
        cPhoneNo   = @PhoneNumber,
        cFax       = @FaxNumber,
        cEmail     = @Email,
        cPassword  = @Password
    WHERE ClientNo = @Id";

    using (var connection = new SqlConnection(@"..."))
    {
        connection.Open();
        var command = new SqlCommand(updateSql, connection);
        var args = command.Parameters;

        args.Add("@FirstName", customer.FirstName);
        args.Add("@LastName", customer.LastName);
        args.Add("@DateOfBirth", customer.DateOfBirth);
        args.Add("@Address", customer.Address);
        args.Add("@ZipCode", customer.ZipCode);
        args.Add("@PhoneNumber", customer.PhoneNumber);
        args.Add("@FaxNumber", customer.FaxNumber);
        args.Add("@Email", customer.Email);
        args.Add("@Password", customer.Password);
        args.Add("@Id", customer.Id);

        command.ExecuteNonQuery();
    }

    UFlag = "T";
}

The SQL allows you to update all columns in one command instead of issuing an UPDATE for each form field. Only updating one field at a time will cause more traffic to your database unnecessarily.

When the user first visits the page and you populate the form fields, all the fields should be populated from the database.

Additional reading

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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