Example : All Integrated Codes in C#.

Table Creation Code


CREATE TABLE UserRegistration
(
    Slno INT IDENTITY(1,1) PRIMARY KEY,   

    UserName VARCHAR(100) NOT NULL,

    Password VARCHAR(255) NOT NULL,

    Address VARCHAR(250),

    MobileNo VARCHAR(15),

    Email VARCHAR(100),

    DOB DATE,

    Gender VARCHAR(10),

    NonMatric BIT DEFAULT 0,

    Matric BIT DEFAULT 0,

    Intermediate BIT DEFAULT 0,

    GraduationPostGraduation BIT DEFAULT 0,

    Nationality VARCHAR(50),

    Remarks VARCHAR(500)
);

NB: Here, IDENTITY(1,1) automatically creates and increment value by 1 in SLno field of this table in the SQL Server database 2014.

============================================================================================================

using System;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        //connectivity code

        SqlConnection con = new SqlConnection(
            // @"Data Source=Servername;Initial Catalog=DatabaseName;Integrated Security=True");
            //@"Data Source=.\SQLEXPRESS;Initial Catalog=DatabaseName;Integrated Security=True"
           @"Data Source=RKM;Initial Catalog=CSharpDB;Integrated Security=True");

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {            
            //Connectivity Confirmation Message Display
            
            try
            {
                // Open SQL Server connection
                con.Open();

                MessageBox.Show(
                    "Database Connected Successfully.",
                    "Connection",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    "Connection Failed:\n" + ex.Message,
                    "Database Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
            finally
            {
                // Close connection
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }


  
            CmbNationality.Items.Add("Select One");
            CmbNationality.Items.Add("India");
            CmbNationality.Items.Add("USA");
            CmbNationality.Items.Add("SriLanka");
            CmbNationality.Items.Add("Bhutan");
            CmbNationality.Items.Add("Nepal");
            CmbNationality.Items.Add("Other");

            
            // No item selected initially
            //CmbNationality.SelectedIndex = -1;

            // First item selected initially
            CmbNationality.SelectedIndex = 0;


            
            DtpDob.Format = DateTimePickerFormat.Custom;
            DtpDob.CustomFormat = "dd MMM yyyy";
            

            Clear();
        }

        private void UrBtnExit_Click(object sender, EventArgs e)
        {
            //this.Close(); 
            DialogResult result;

            result = MessageBox.Show(
                "Do you want to exit?",
                "Exit Confirmation",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                Application.Exit();
            }
        }

        private void Clear()
        {
            TxtSlno.Text = "";

            TxtUserId.Clear();      //TxtUserId.Text = "";

            TxtAddress.Clear();

            TxtPass.Clear();

            TxtCPass.Clear();

            TxtMob.Text = "";

            DtpDob.Value = DateTime.Today;

            RdbMale.Checked = false;
            RdbFemale.Checked = false;
            RdbOther.Checked = false;

            ChkNonMatric.Checked = false;
            ChkMatric.Checked = false;
            ChkItermediate.Checked = false;
            ChkGradPostG.Checked = false;


            // First item selected initially
            CmbNationality.SelectedIndex = 0;

            // No item selected initially
            //CmbNationality.SelectedIndex = -1;

            // to remove typed text
            //CmbNationality.Text = "";


            RtbRemarks.Text = "N/A";
            //RtbRemarks.Text = ""; //Rich text box
            //RtbRemarks.Clear();

            //listBox1.ClearSelected();            
            //listBox1.Items.Clear(); 

            //pictureBox1.Image = null;

            //label1.Text = ""; 

            TxtSlno.Focus();
        }
        
        private void UrBtnClear_Click(object sender, EventArgs e)
        {

            Clear();
        }

        private void UrBtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // -----------------------------------------
                // Validate User Name
                // -----------------------------------------
                if (TxtUserId.Text.Trim() == "")
                {
                    MessageBox.Show("Please enter User Name/Id.",
                                    "Validation",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);

                    TxtUserId.Focus();
                    return;
                }


                // -----------------------------------------
                // Validate Password
                // -----------------------------------------
                if (TxtPass.Text.Trim() == "")
                {
                    MessageBox.Show("Please enter Password.",
                                    "Validation",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);

                    TxtPass.Focus();
                    return;
                }


                // -----------------------------------------
                // Validate Confirm Password
                // -----------------------------------------
                if (TxtCPass.Text.Trim() == "")
                {
                    MessageBox.Show("Please enter Confirm Password.",
                                    "Validation",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);

                    TxtCPass.Focus();
                    return;
                }


                // -----------------------------------------
                // Compare Password and Confirm Password
                // -----------------------------------------
                if (TxtPass.Text != TxtCPass.Text)
                {
                    MessageBox.Show("Password and Confirm Password do not match.",
                                    "Validation",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);

                    TxtCPass.Focus();
                    return;
                }


                // -----------------------------------------
                // Validate Mobile Number
                // -----------------------------------------
                if (TxtMob.Text.Trim() == "")
                {
                    MessageBox.Show("Please enter Mobile Number.");
                    TxtMob.Focus();
                    return;
                }


                // -----------------------------------------
                // Validate Gender
                // -----------------------------------------
                if (RdbMale.Checked == false &&
                    RdbFemale.Checked == false &&
                    RdbOther.Checked == false)
                {
                    MessageBox.Show("Please select Gender.");
                    return;
                }


                // -----------------------------------------
                // Validate Nationality
                // -----------------------------------------
                if (CmbNationality.SelectedIndex == -1)
                {
                    MessageBox.Show("Please select Nationality.");
                    CmbNationality.Focus();
                    return;
                }


                // -----------------------------------------
                // Get Gender
                // -----------------------------------------
                string gender = "";

                if (RdbMale.Checked == true)
                {
                    gender = "Male";
                }
                else if (RdbFemale.Checked == true)
                {
                    gender = "Female";
                }
                else if (RdbOther.Checked == true)
                {
                    gender = "Other";
                }


                // -----------------------------------------
                // SQL INSERT command
                // -----------------------------------------
                string sql = @"INSERT INTO UserRegistration
                       (
                           UserName,
                           Password,
                           Address,
                           MobileNo,
                           Email,
                           DOB,
                           Gender,
                           NonMatric,
                           Matric,
                           Intermediate,
                           GraduationPostGraduation,
                           Nationality,
                           Remarks
                       )
                       VALUES
                       (
                           @UserName,
                           @Password,
                           @Address,
                           @MobileNo,
                           @Email,
                           @DOB,
                           @Gender,
                           @NonMatric,
                           @Matric,
                           @Intermediate,
                           @Graduation,
                           @Nationality,
                           @Remarks
                       ) ";


                // -----------------------------------------
                // Create SQL Command
                // -----------------------------------------
                SqlCommand cmd = new SqlCommand(sql, con);


                // -----------------------------------------
                // Pass TextBox values
                // -----------------------------------------
                cmd.Parameters.AddWithValue("@UserName",
                                            TxtUserId.Text.Trim());

                cmd.Parameters.AddWithValue("@Password",
                                            TxtPass.Text);

                cmd.Parameters.AddWithValue("@Address",
                                            TxtAddress.Text.Trim());

                cmd.Parameters.AddWithValue("@MobileNo",
                                            TxtMob.Text.Trim());

                cmd.Parameters.AddWithValue("@Email",
                                            TxtEmail.Text.Trim());


                // -----------------------------------------
                // Pass DateTimePicker value
                // -----------------------------------------
                cmd.Parameters.AddWithValue("@DOB",
                                            DtpDob.Value.Date);


                // -----------------------------------------
                // Pass RadioButton value
                // -----------------------------------------
                cmd.Parameters.AddWithValue("@Gender",
                                            gender);


                // -----------------------------------------
                // Pass CheckBox values
                // true  = 1
                // false = 0
                // -----------------------------------------
                cmd.Parameters.AddWithValue("@NonMatric",
                                            ChkNonMatric.Checked);

                cmd.Parameters.AddWithValue("@Matric",
                                            ChkMatric.Checked);

                cmd.Parameters.AddWithValue("@Intermediate",
                                            ChkItermediate.Checked);

                cmd.Parameters.AddWithValue("@Graduation",
                                            ChkGradPostG.Checked);


                // -----------------------------------------
                // Pass ComboBox value
                // -----------------------------------------
                cmd.Parameters.AddWithValue("@Nationality",
                                            CmbNationality.Text);


                // -----------------------------------------
                // Pass RichTextBox value
                // -----------------------------------------
                cmd.Parameters.AddWithValue("@Remarks",
                                            RtbRemarks.Text.Trim());


                // -----------------------------------------
                // Open database connection
                // -----------------------------------------
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }


                // -----------------------------------------
                // Execute INSERT command
                // -----------------------------------------
                int result = cmd.ExecuteNonQuery();


                // -----------------------------------------
                // Check whether record was saved
                // -----------------------------------------
                if (result > 0)
                {
                    MessageBox.Show("Record Saved Successfully.",
                                    "Save",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);

                    Clear();
                }
                else
                {
                    MessageBox.Show("Record could not be saved.");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message,
                                "Database Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            finally
            {
                // Close database connection
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
        }       
        
    }
}

Loading

Categories: C#

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.