Saturday, 23 July 2011

checking data on sql through win form weather entry is added or failed or no double entry


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 WindowsFormsApplication8
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        int flag = 0;
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                SqlConnection conn = new SqlConnection("server=WEBNET;database=scott;user=sa;password=aptech");
                conn.Open();
                string select = "select * from reg";
                SqlCommand comm = new SqlCommand(select, conn);
                SqlDataReader dr = comm.ExecuteReader();
                while (dr.Read())
                {
                    if (dr["rollno"].ToString() == textBox1.Text)
                    {
                        MessageBox.Show("Record already exists");
                        flag = 1;
                    }
                }
                if (textBox1.Text.Equals("") || textBox2.Text.Equals("") || textBox3.Text.Equals("") || textBox4.Text.Equals(""))
                {
                    MessageBox.Show("values cannot be empty");
                }
                else if(flag==0)
                {
                    string insert;
                    insert = "insert into reg values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')";
                    SqlCommand comm1 = new SqlCommand(insert, conn);
                    flag = 0;
                    dr.Close();
                    comm1.ExecuteNonQuery();
               
               
               
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Occured");
            }
        }
       
    }
}

No comments:

Post a Comment