Program C Sharp Input Data Ke SQL Server

Pada artikel berikut ini akan di bahas untuk menyimpan data  ke database SQL Server 2005.
Pada form ini hanya menambah 1 button Simpan saja.

Berikut listing program input data ke sql server

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 CS_Searching
{
    public partial class Form1 : Form
    {
        SqlConnection Conn;
        SqlCommand CMD;
        SqlDataReader DR;      
       
        string SQL = "";

        public Form1()
        {
            InitializeComponent();
        }

        void koneksiDB()
        {
            SQL = " Data Source=ALDY-AAN ; initial catalog=pegawai; integrated security=true";
            Conn = new SqlConnection(SQL);

            if (Conn.State == ConnectionState.Closed)
            {
                Conn.Open();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            koneksiDB();
        }

        private void Gol_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                //Tambahkan T pada Perintah SELEC
        SQL = "Selec * From Golongan where kdgol='" + Gol.Text + "'";
                CMD = new SqlCommand(SQL, Conn);
                DR = CMD.ExecuteReader();
                DR.Read();
                if (DR.HasRows == true)
                {
                    Gaji.Text = DR["Gaji"].ToString();                   
                }
                else
                {
                    Gaji.Focus();
                }
                DR.Close();               
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SQL = "Insert Into Golongan(kdgol, gaji) values('";
            SQL = SQL + Gol.Text + "'," + Gaji.Text + ")";
            CMD = new SqlCommand(SQL, Conn);
            CMD.ExecuteScalar();
            MessageBox.Show("Data Sudah Tersimpan !");
        }

    }
}


Sumber : Mesran.net
Back to top