Saturday, 23 July 2011

C# Sharp WinForm Ceating Connection To SqlServer adding,delete,update Data Through Textbox


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 mydatabase
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection sc = new SqlConnection("Server=LAB2-86;Database=ApStudents;user=sa;password=aptech");
            string insert = "insert into Students values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "')";
            SqlCommand cm = new SqlCommand(insert, sc);
            sc.Open();
            //cm.ExecuteNonQuery();
            try
            {
                cm.ExecuteNonQuery();
                MessageBox.Show("Data Insert Successfully");
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            sc.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SqlConnection sc = new SqlConnection("Server=LAB2-86;Database=ApStudents;user=sa;password=aptech");
            string delete = "delete from Students where std_ID=('" + textBox1.Text + "')";
            SqlCommand cm = new SqlCommand(delete, sc);
            sc.Open();
            cm.ExecuteNonQuery();
            MessageBox.Show("Data Delete Successfully");
            sc.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            SqlConnection sc = new SqlConnection("Server=LAB2-86;Database=ApStudents;user=sa;password=aptech");
            string update = "update Students set std_ID='" + textBox1.Text + "',S_Name='" + textBox2.Text + "',S_Address='" + textBox3.Text + "' where std_ID='" + textBox1.Text + "' ";
            SqlCommand cm = new SqlCommand(update, sc);
            sc.Open();
            cm.ExecuteNonQuery();
            MessageBox.Show("Data Update Successfully");
            sc.Close();
        }
    }
}

No comments:

Post a Comment