Saturday 8 December 2012

How to create stored procedure sql with C#.net

 Create store procedure  in sql 

Create Table:

CREATE TABLE tbl_StudentDetails
(
Sno int not null,
StudName varchar(50) not null,
Studentid varchar(50) primary key ,
Gender Varchar(50) not null
)

Then, Create procedure like Insert Query

CREATE PROCEDURE sp_InsertStudentDetails

@Sno int ,
@StudName varchar(50) ,
@Studentid varchar(50) ,
@Gender Varchar(50)
AS
INSERT INTO  tbl_StudentDetails(Sno,StudentName,Studentid,Gender)VALUES(@Sno,@StudentName,@studentId,@Gender)

C#:

Class File:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace GLOBAL_TRACKING_SYSTEM
{
    /// <summary>
    /// Database operations
    /// </summary>
    class clsDboperations
    {
        SqlConnection con;
        string error = string.Empty;
        string conString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;

     
       
        public clsDboperations()
        {
            con = new SqlConnection(conString);
        }
        #region Methods
        public Boolean methodNonquery(string query)
        {
            try
            {
                SqlCommand cmd = new SqlCommand(query, con);
                con.Open();
                cmd.ExecuteNonQuery();
                return true;
            }
            catch (SqlException ex)
            {
                error = ex.Message;
                return false;
            }
            finally
            {
                con.Close();
            }
        }
}

GUI:


  int sno = 0;
  string studentName = string.Empty;
  string studentId = string.Empty;
  string gender = string.Empty;

sno=txtSno.Text.Trim();
studentName=txtStudent.Text();

studentId=txtStudentid.Text();
gender=cmbGender.Text.Trim();




 string insQry = string.Empty;
bool exeQry=false;
                insQry = string.Format(" sp_InsertStudentDetails {0},'{1}','{2}','{3}' ",sno,studentName,studentId ,gender);
             exeQry=  obj.methodNonquery(insQry);


  if (exeQry == true)
                        {
                            MessageBox.Show("Sucessfully registered", "Sucess", MessageBoxButtons.OK, MessageBoxIcon.Information);
                       
                        }
                        else
                        {
                            MessageBox.Show("un Sucessfully registered", "Sucess", MessageBoxButtons.OK, MessageBoxIcon.Error);

                        }

               











4 comments: