Passing Parameter in C# to SQL Stored Procedure

Write a SQL Server Stored procedure with Two Parameter. This SQL Server Stored Procedure insert the User Information like Username and Password, you can change as per your requirement.
SET ANSI_NULLSON
GO
SET QUOTED_IDENTIFIERON
GO
— =============================================
— Author:         <Ahmed>
— =============================================
CREATE PROCEDUREInsertUsers
(@UserName varchar(25),@UserPWD varchar(20))
      
AS
BEGIN
     — SET NOCOUNT ON added to prevent extra result sets from
     — interfering with SELECT statements.
     SET NOCOUNT ON;
    — Insert statements for procedure here
     INSERT INTO Lib_Users(User_Name,User_Password)
     VALUES(@USERNAME,@USERPWD);   
END
GO
Now this C# program passing parameter to stored procdure.
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Data.SqlClient;
namespacePassingParameterinCSharptoSqlserver
{
    public partial class Form1 : Form
    {
        stringcon = “Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=True”;
  publicForm1()
  {
  InitializeComponent();
  }
  privatevoid button1_Click(objectsender, EventArgs e)
  { 

SqlConnection cnn =newSqlConnection(con);

  try
 {
  cnn.Open();
  SqlCommandSqlCmd = new SqlCommand(“InsertUsers”,cnn);
  SqlCmd.CommandType = CommandType.StoredProcedure;
              
              //passing parameter to stored procedure
             
                SqlCmd.Parameters.AddWithValue(“@USERNAME”, textBox2.Text);
                SqlCmd.Parameters.AddWithValue(“@USERPWD”, textBox3.Text);
                SqlCmd.ExecuteNonQuery();
                MessageBox.Show(“Record Inserted Successfully….”);
                cnn.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
                cnn.Close();
             }
        }
        privatevoid button2_Click(objectsender, EventArgs e)
        {
            this.Close();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *