Kamis, 19 September 2013

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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
  
        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 />
    </div>

    </form>
</body>
</html>
Codebehind
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"))
        {
            con.Open();

            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";
            }


        }

    }
}
Output
How to use AddWithValue Method in ASP.NET

Tidak ada komentar:

Posting Komentar