How to use AddWithValue Method in ASP.NET

Adds a value to the end of the System.Data.SqlClient.SqlParameterCollection. Syntax of the method is

variable of SqlCommand.Parameters .AddWithValue (String parameterName , Object value);
using Parameters collection you can insert values to the database.

Lets take an example how to insert item into database table.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
        Enter name :
        <asp:TextBox ID="TextBox1" runat="server" Width="183px"></asp:TextBox>
        <br />
        Enter Address :
        <asp:TextBox ID="TextBox2" runat="server" Width="183px"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click1"
            Text="Submit" />
        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label>
        <br />
        <br />

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;
using System.Data;

public partial class Default4 : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)

    protected void Button1_Click1(object sender, EventArgs e)
        using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"))

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.Parameters.AddWithValue("@nameprameter", TextBox1.Text);
            cmd.Parameters.AddWithValue("@Addressparameter", TextBox2.Text);
            cmd.CommandText = "insert into [mytab](name,address)values(@nameprameter,@Addressparameter)";
            int a = cmd.ExecuteNonQuery();
            if (a > 0)
                Label1.Text = "insert data";


How to use AddWithValue Method in ASP.NET

Posted on by Jacob Lefore | No comments


Post a Comment