C# and SQL

Core

Member
Jan 23, 2010
3,120
195
0
Milky Way/Local Cluster/Local Sol/Earth
Code:
.CS File

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;

namespace DataBase_UserDetails
{
    public partial class Form1 : Form
    {
        string connectionString;

        public Form1()
        {
            InitializeComponent();
            connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=Database1 - Copy.mdf;Integrated Security=True;User Instance=True";
        }

        //Create a New Table
        private void btnCreate_Click(object sender, EventArgs e)
        {
            SqlConnection SqlCon = new SqlConnection(connectionString);
            SqlCon.Open(); //open the connection
            string commandStr = "CREATE TABLE users("+
                "user_id INT NOT NULL," +
                "user_name VARCHAR(40) NOT NULL," +
                "user_email VARCHAR(40) NOT NULL," +
                "user_pass VARCHAR(40) NOT NULL," +
                "user_registration_date DATETIME NOT NULL," +
                "user_state VARCHAR(10) NOT NULL," +
                "PRIMARY KEY(user_id))";
            SqlCommand cmd = new SqlCommand(commandStr, SqlCon);

            try
            {
                cmd.ExecuteNonQuery();
                SqlCon.Close();
                
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message, "Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }


        }

        //Create a DataBase
        private void btn_newDB_Click(object sender, EventArgs e)
        {
            string commandStr = "CREATE DATABASE Core";
            SqlCommand cmd = new SqlCommand(commandStr);
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //create new field
        private void btnInsert_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(connectionString);
            con.Open(); //open the connection
            string commandStr = "INSERT INTO users(user_id, user_name, user_email, user_pass, user_registration_date, user_state)" +
                 " VALUES(@userID,@userName,@email,@userPass,@date,@userState)";

            SqlCommand cmd = new SqlCommand(commandStr, con);//create an object from the sqlcommand
            cmd.Parameters.AddWithValue("@userID", txtID.Text);
            cmd.Parameters.AddWithValue("@userName", txtName.Text);
            cmd.Parameters.AddWithValue("@email", txtEmail.Text);
            cmd.Parameters.AddWithValue("@userPass", txtPass.Text);
            cmd.Parameters.AddWithValue("@date", DateTime.Now);
            cmd.Parameters.AddWithValue("@userState", txtState.Text);

            try
            {
                cmd.ExecuteNonQuery();
                con.Close();
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }
        }

        //UPDATE
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();//open the connection between the database and the application
            string commandString = "UPDATE users SET "+
           "user_name=@userName,user_email=@email,user_pass=@userPass,"+
           "user_registration_date=@date,user_state=@userState WHERE user_id=@selectedID";

            string selectedID = treeView1.SelectedNode.Text;//get the selected index value
            SqlCommand cmd = new SqlCommand(commandString, con);//make the SQL command object
            cmd.Parameters.AddWithValue("@selectedID", selectedID);//replace the @selectedId with selected value on treenode
            //get the selected index value from the treeview 
            //and then replace that with SQL string command
            //therefore the condition is id everything related that ID will be updated.
            //following fields will replace the txt boxes with SQL command parameters
            cmd.Parameters.AddWithValue("@userName",txtName.Text);
            cmd.Parameters.AddWithValue("@email",txtEmail.Text);
            cmd.Parameters.AddWithValue("@userPass",txtPass.Text);
            cmd.Parameters.AddWithValue("@date",DateTime.Now);
            cmd.Parameters.AddWithValue("@userState",txtState.Text);

            try
            {
                cmd.ExecuteNonQuery();//execute the command
                con.Close();
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }

        }

        //SELECT ALL
        private void btnSelectAll_Click(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();//clear all nodes if there are any remaining
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            string commandString = "SELECT * FROM users";//get everything from the users table
            SqlCommand cmd = new SqlCommand(commandString, con);
            SqlDataReader reader;

            try
            {
                reader = cmd.ExecuteReader();
                
                while (reader.Read())
                {
                    TreeNode mainNode =  treeView1.Nodes.Add(reader["user_id"].ToString());
                    mainNode.Nodes.Add(reader["user_name"].ToString());
                    mainNode.Nodes.Add(reader["user_email"].ToString());
                    mainNode.Nodes.Add(reader["user_pass"].ToString());
                    mainNode.Nodes.Add(reader["user_registration_date"].ToString());
                    mainNode.Nodes.Add(reader["user_state"].ToString());
                }
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }

        }

        //Delete data Field
        private void btnDelete_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            string commandStr = "DELETE FROM users WHERE user_id=@userID";//just select the primary key so it will delete the entire row
            SqlCommand cmd = new SqlCommand(commandStr, con);
            cmd.Parameters.AddWithValue("userID", treeView1.SelectedNode.Text);

            try
            {
                cmd.ExecuteNonQuery();
                con.Close();
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }
        }

        //Select the TreeNode
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode indexNode = treeView1.SelectedNode;//get the selected node
            txtID.Text = indexNode.Text;//get the index id
            txtName.Text = indexNode.Nodes[0].Text;
            txtEmail.Text = indexNode.Nodes[1].Text;
            txtPass.Text = indexNode.Nodes[2].Text;
            txtDate.Text = indexNode.Nodes[3].Text;
            txtState.Text = indexNode.Nodes[4].Text;
        }

        //search Keyword
        //IN SQL SERVER EXPREE DON"T USE '' SINGLE QUOTATION MARKS OR % WHEN COMPARE LIKE OR NOT LIKE
        //NEARLY EQUALITY
        private void btnSearch_Click(object sender, EventArgs e)
        {
            /*
             * user_name=@userName,user_email=@email,user_pass=@userPass,"+
           "user_registration_date=@date,user_state=@userState
            */
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            string commandStr = "SELECT * FROM users WHERE (user_name LIKE @userName) OR" +
                "(user_email LIKE @userEmail) OR (user_pass LIKE @userPass) OR " +
                "(user_registration_date LIKE @userReg) OR (user_state LIKE @userState)";

            SqlCommand cmd = new SqlCommand(commandStr, con);
            //replace the parameters with the C# components
            cmd.Parameters.AddWithValue("@userName", txtSearchKey.Text);
            cmd.Parameters.AddWithValue("@userEmail", txtSearchKey.Text);
            cmd.Parameters.AddWithValue("@userPass", txtSearchKey.Text);
            cmd.Parameters.AddWithValue("@userReg", txtSearchKey.Text);
            cmd.Parameters.AddWithValue("@userState", txtSearchKey.Text);

            try
            {
                SqlDataReader reader = cmd.ExecuteReader(); ;
                while (reader.Read())//read the next record if non of record found return 0
                {
                    TreeNode mainNode = treeView1.Nodes.Add(reader["user_id"].ToString());
                    mainNode.Nodes.Add(reader["user_name"].ToString());
                    mainNode.Nodes.Add(reader["user_email"].ToString());
                    mainNode.Nodes.Add(reader["user_pass"].ToString());
                    mainNode.Nodes.Add(reader["user_registration_date"].ToString());
                    mainNode.Nodes.Add(reader["user_state"].ToString());
                }
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }
            
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();
        }

    }
}
Instructions
First add a Server SQL Database into the solution explorer and just proceed with above codes.!




Copyright Notice
All Source Codes belong to Core and don't mess with my codes without my permission.

I made this on another forum which I can't mention in here.
7.gif

but thought make the same thing in here is useful.
 

Core

Member
Jan 23, 2010
3,120
195
0
Milky Way/Local Cluster/Local Sol/Earth
Code:
form1.designer.cs


namespace DataBase_UserDetails
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.btnCreate = new System.Windows.Forms.Button();
            this.treeView1 = new System.Windows.Forms.TreeView();
            this.btn_newDB = new System.Windows.Forms.Button();
            this.btnSelectAll = new System.Windows.Forms.Button();
            this.btnInsert = new System.Windows.Forms.Button();
            this.btnDelete = new System.Windows.Forms.Button();
            this.btnUpdate = new System.Windows.Forms.Button();
            this.txtID = new System.Windows.Forms.TextBox();
            this.txtName = new System.Windows.Forms.TextBox();
            this.txtEmail = new System.Windows.Forms.TextBox();
            this.txtPass = new System.Windows.Forms.TextBox();
            this.txtState = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.txtDate = new System.Windows.Forms.DateTimePicker();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.label6 = new System.Windows.Forms.Label();
            this.btnSearch = new System.Windows.Forms.Button();
            this.txtSearchKey = new System.Windows.Forms.TextBox();
            this.label7 = new System.Windows.Forms.Label();
            this.btnClear = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // btnCreate
            //
            this.btnCreate.Location = new System.Drawing.Point(47, 393);
            this.btnCreate.Name = "btnCreate";
            this.btnCreate.Size = new System.Drawing.Size(108, 43);
            this.btnCreate.TabIndex = 0;
            this.btnCreate.Text = "Create a Table";
            this.btnCreate.UseVisualStyleBackColor = true;
            this.btnCreate.Click += new System.EventHandler(this.btnCreate_Click);
            //
            // treeView1
            //
            this.treeView1.Location = new System.Drawing.Point(43, 34);
            this.treeView1.Name = "treeView1";
            this.treeView1.Size = new System.Drawing.Size(364, 277);
            this.treeView1.TabIndex = 1;
            this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
            //
            // btn_newDB
            //
            this.btn_newDB.Location = new System.Drawing.Point(170, 393);
            this.btn_newDB.Name = "btn_newDB";
            this.btn_newDB.Size = new System.Drawing.Size(123, 43);
            this.btn_newDB.TabIndex = 2;
            this.btn_newDB.Text = "Create New DataBase";
            this.btn_newDB.UseVisualStyleBackColor = true;
            this.btn_newDB.Click += new System.EventHandler(this.btn_newDB_Click);
            //
            // btnSelectAll
            //
            this.btnSelectAll.Location = new System.Drawing.Point(47, 346);
            this.btnSelectAll.Name = "btnSelectAll";
            this.btnSelectAll.Size = new System.Drawing.Size(108, 41);
            this.btnSelectAll.TabIndex = 3;
            this.btnSelectAll.Text = "Retrieve Data";
            this.btnSelectAll.UseVisualStyleBackColor = true;
            this.btnSelectAll.Click += new System.EventHandler(this.btnSelectAll_Click);
            //
            // btnInsert
            //
            this.btnInsert.Location = new System.Drawing.Point(170, 346);
            this.btnInsert.Name = "btnInsert";
            this.btnInsert.Size = new System.Drawing.Size(108, 41);
            this.btnInsert.TabIndex = 4;
            this.btnInsert.Text = "Insert Data";
            this.btnInsert.UseVisualStyleBackColor = true;
            this.btnInsert.Click += new System.EventHandler(this.btnInsert_Click);
            //
            // btnDelete
            //
            this.btnDelete.Location = new System.Drawing.Point(299, 393);
            this.btnDelete.Name = "btnDelete";
            this.btnDelete.Size = new System.Drawing.Size(108, 41);
            this.btnDelete.TabIndex = 5;
            this.btnDelete.Text = "Delete Data";
            this.btnDelete.UseVisualStyleBackColor = true;
            this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
            //
            // btnUpdate
            //
            this.btnUpdate.Location = new System.Drawing.Point(299, 346);
            this.btnUpdate.Name = "btnUpdate";
            this.btnUpdate.Size = new System.Drawing.Size(108, 41);
            this.btnUpdate.TabIndex = 6;
            this.btnUpdate.Text = "Update Data";
            this.btnUpdate.UseVisualStyleBackColor = true;
            this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click);
            //
            // txtID
            //
            this.txtID.Location = new System.Drawing.Point(530, 59);
            this.txtID.Name = "txtID";
            this.txtID.Size = new System.Drawing.Size(179, 20);
            this.txtID.TabIndex = 7;
            //
            // txtName
            //
            this.txtName.Location = new System.Drawing.Point(530, 85);
            this.txtName.Name = "txtName";
            this.txtName.Size = new System.Drawing.Size(179, 20);
            this.txtName.TabIndex = 8;
            //
            // txtEmail
            //
            this.txtEmail.Location = new System.Drawing.Point(530, 189);
            this.txtEmail.Name = "txtEmail";
            this.txtEmail.Size = new System.Drawing.Size(179, 20);
            this.txtEmail.TabIndex = 9;
            //
            // txtPass
            //
            this.txtPass.Location = new System.Drawing.Point(530, 111);
            this.txtPass.Name = "txtPass";
            this.txtPass.Size = new System.Drawing.Size(179, 20);
            this.txtPass.TabIndex = 10;
            //
            // txtState
            //
            this.txtState.Location = new System.Drawing.Point(530, 163);
            this.txtState.Name = "txtState";
            this.txtState.Size = new System.Drawing.Size(179, 20);
            this.txtState.TabIndex = 11;
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(425, 66);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(64, 13);
            this.label1.TabIndex = 13;
            this.label1.Text = "Enter the ID";
            //
            // txtDate
            //
            this.txtDate.Location = new System.Drawing.Point(530, 137);
            this.txtDate.Name = "txtDate";
            this.txtDate.Size = new System.Drawing.Size(179, 20);
            this.txtDate.TabIndex = 14;
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(425, 92);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(81, 13);
            this.label2.TabIndex = 15;
            this.label2.Text = "Enter the Name";
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(425, 118);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(99, 13);
            this.label3.TabIndex = 16;
            this.label3.Text = "Enter the Password";
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(425, 144);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(76, 13);
            this.label4.TabIndex = 17;
            this.label4.Text = "Enter the Date";
            //
            // label5
            //
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(425, 170);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(78, 13);
            this.label5.TabIndex = 18;
            this.label5.Text = "Enter the State";
            //
            // label6
            //
            this.label6.AutoSize = true;
            this.label6.Location = new System.Drawing.Point(425, 196);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(78, 13);
            this.label6.TabIndex = 19;
            this.label6.Text = "Enter the Email";
            //
            // btnSearch
            //
            this.btnSearch.Location = new System.Drawing.Point(604, 350);
            this.btnSearch.Name = "btnSearch";
            this.btnSearch.Size = new System.Drawing.Size(105, 33);
            this.btnSearch.TabIndex = 20;
            this.btnSearch.Text = "Search";
            this.btnSearch.UseVisualStyleBackColor = true;
            this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
            //
            // txtSearchKey
            //
            this.txtSearchKey.Location = new System.Drawing.Point(565, 317);
            this.txtSearchKey.Name = "txtSearchKey";
            this.txtSearchKey.Size = new System.Drawing.Size(144, 20);
            this.txtSearchKey.TabIndex = 21;
            //
            // label7
            //
            this.label7.AutoSize = true;
            this.label7.Location = new System.Drawing.Point(511, 320);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(48, 13);
            this.label7.TabIndex = 22;
            this.label7.Text = "Keyword";
            //
            // btnClear
            //
            this.btnClear.Location = new System.Drawing.Point(604, 389);
            this.btnClear.Name = "btnClear";
            this.btnClear.Size = new System.Drawing.Size(105, 33);
            this.btnClear.TabIndex = 23;
            this.btnClear.Text = "Clear";
            this.btnClear.UseVisualStyleBackColor = true;
            this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(758, 467);
            this.Controls.Add(this.btnClear);
            this.Controls.Add(this.label7);
            this.Controls.Add(this.txtSearchKey);
            this.Controls.Add(this.btnSearch);
            this.Controls.Add(this.label6);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.txtDate);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.txtState);
            this.Controls.Add(this.txtPass);
            this.Controls.Add(this.txtEmail);
            this.Controls.Add(this.txtName);
            this.Controls.Add(this.txtID);
            this.Controls.Add(this.btnUpdate);
            this.Controls.Add(this.btnDelete);
            this.Controls.Add(this.btnInsert);
            this.Controls.Add(this.btnSelectAll);
            this.Controls.Add(this.btn_newDB);
            this.Controls.Add(this.treeView1);
            this.Controls.Add(this.btnCreate);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.Name = "Form1";
            this.Text = "Main Window";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button btnCreate;
        private System.Windows.Forms.TreeView treeView1;
        private System.Windows.Forms.Button btn_newDB;
        private System.Windows.Forms.Button btnSelectAll;
        private System.Windows.Forms.Button btnInsert;
        private System.Windows.Forms.Button btnDelete;
        private System.Windows.Forms.Button btnUpdate;
        private System.Windows.Forms.TextBox txtID;
        private System.Windows.Forms.TextBox txtName;
        private System.Windows.Forms.TextBox txtEmail;
        private System.Windows.Forms.TextBox txtPass;
        private System.Windows.Forms.TextBox txtState;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.DateTimePicker txtDate;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Label label6;
        private System.Windows.Forms.Button btnSearch;
        private System.Windows.Forms.TextBox txtSearchKey;
        private System.Windows.Forms.Label label7;
        private System.Windows.Forms.Button btnClear;