Advertisement
I created a New Project in windows form using c#
Now in Form1.cs, I designed my UI
I created a table name Employee in my database.
Now i am creating the Stored Procedure for Inserting the data in database.
USE [dotnetdb] GO /****** Object: StoredProcedure [dbo].[SP_InsertEmpinfo] Script Date: 07/23/2013 13:54:06 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO Create procedure [dbo].[SP_InsertEmpinfo] ( @EmpId nvarchar(50), @EmpName nvarchar(50), @EmpAddress nvarchar(50), @EmpDesignation nvarchar(50) ) As Begin Insert into Employee (EmpId,EmpName,EmpAddress,EmpDesignation) values (@EmpId,@EmpName,@EmpAddress,@EmpDesignation) end GONow i am writing the code on buttonclick in Form1.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace CheckId { public partial class Form1 : Form { public string empid; public Form1() { InitializeComponent(); } private void submit_Click(object sender, EventArgs e) { using (SqlConnection con = new SqlConnection("Data Source = CHINNU;Initial Catalog = dotnetdb;Uid = sa;Password = password123;")) { if (!empId()) { } else { SqlCommand cmd = new SqlCommand("SP_InsertEmpinfo", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@EmpId", SqlDbType.NVarChar).Value = txtempid.Text; cmd.Parameters.Add("@EmpName", SqlDbType.NVarChar).Value = txtempname.Text; cmd.Parameters.Add("@EmpAddress", SqlDbType.NVarChar).Value = txtempaddress.Text; cmd.Parameters.Add("@EmpDesignation", SqlDbType.NVarChar).Value = txtdesignation.Text; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } } public bool empId() { using (SqlConnection con = new SqlConnection("Data Source = CHINNU;Initial Catalog = dotnetdb;Uid = sa;Password = password123;")) { con.Open(); string query = "select EmpId from employee where EmpId= '" + txtempid.Text + "'"; SqlCommand cmd = new SqlCommand(query, con); SqlDataReader dr; dr = cmd.ExecuteReader(); while (dr.Read()) { empid = dr["EmpId"].ToString(); if (empid != "0") { MessageBox.Show("Id Already Exists"); return false; } con.Close(); } return true; } } } }
Now I am adding App.config for Connection.
Now Press F5.
Now I am Entering the employee information as shown below.
Now i inserted the employee information in my db,again i am trying to inserting the same information.
It throws an error message like this.
Output:
0 comments:
Post a Comment