|
SqlParameter class is responsible to send the parameters to the queries. You can create any number of parameters and associate that with the command object. There are several ways to create the parameter for a command object.
1. cmd.Parameter.add (“variable Name”, “value”) cmd.Parameter.add (new SqlParameter (“variableName”,”value”))
2. cmd.Parameter.add (“@lastName”, sqlDbType.Varchar).Value=”Vik”
Example to pass Parameter in SQL Queries:
Note :-The following example will find the name of the employee whose employee Id has been entered in the textbox.
ParameterPassing.aspx
<%@ Page Language ="VB" AutoEventWireup ="false" CodeFile ="Example6.aspx.vb" Inherits ="Example6" %>
<! 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">
</head>
<body>
<form id ="form1" runat ="server">
<div>
<asp:Label ID ="Label1" runat ="server" Text ="Enter EmpID Between (1-7)"></asp:Label>
<asp:TextBox ID ="txtEmpId" runat ="server"></ asp:TextBox>
<asp:Button ID ="btnSubmit" runat ="server" Text ="Button"/>
<asp:Label ID ="Label2" runat ="server" Text ="Employee Name is:"></asp:Label>
<asp:Label ID ="lblEmpName" runat ="server"></asp:Label></div>
</form>
</body>
</html>
ParameterPassing.aspx.vb
Imports System
Imports System.Data
Imports System.Data.SqlClient
Partial Class Example6 Inherits System.Web.UI.Page
Protected Sub Page_Load( ByVal sender As Object , ByVal e As System.EventArgs) Handles Me .Load
Label2.Visible = False
lblEmpName.Visible = False
End Sub
Protected Sub btnSubmit_Click( ByVal sender As Object , ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim con As SqlConnection
Dim cmd As SqlCommand
con = New SqlConnection( "Data Source=localhost;Initialcatalog=TestDB;UID=sa;pwd=sa" )
cmd = New SqlCommand()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.Parameters.Add( "@EmpId" , SqlDbType.NVarChar).Value = txtEmpId.Text
cmd.CommandText = "select empName from tblEmp where empId=@EmpId"
con.Open()
Label2.Visible = True
lblEmpName.Visible = True
lblEmpName.Text = cmd.ExecuteScalar
con.Close()
End Sub
End Class |