Free Code Snippets in C#, Net Framework, Office 365, ASP.Net,WPF, Visual Studio, SQL Server, Antivirus free
#

 

 

Code to the online tutorial

 

#CRUD example: how to view, add, delete and update record data in a local SQL Database in Winforms, WPF

 

 

Simple Demo Winforms Example with a list of cars, an an Add- Delete- and Update Button

 

 

Video Tutorial at Youtube

 

Local database with SQL Server

The local database example had a simple table with cars

 

With the following database table definition

CREATE TABLE [dbo].[tbl_Cars] (

    [IDCar] INT            IDENTITY (1, 1) NOT NULL,

    [Car]   NVARCHAR (255) NULL,

    PRIMARY KEY CLUSTERED ([IDCar] ASC)

);

 

 

 

 

C# Code of the example

In Visual Studio

Code under Form1.cs

 

Complet C# Code of Form1.cs

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

 

using System.Data.SqlClient;  //SQL Server local DB

 

 

namespace dbTest03

{

    public partial class Form1 : Form

    {

        #region Forms

        //--------------------------------< region:Forms >--------------------------

        public Form1()

        {

            InitializeComponent();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            load_List();

        }

        //--------------------------------</ region:Forms >--------------------------

        #endregion /Form

 

 

        #region Buttons

        //--------------------------------< region:Buttons >--------------------------

        private void btnAdd_Click(object sender, EventArgs e)

        {

            add_Entry_to_Database();  

        }

        private void btnDelete_Click(object sender, EventArgs e)

        {

            delete_Row_of_Database();

        }

        private void btnUpdate_Click(object sender, EventArgs e)

        {

            update_Entry_in_Database();

        }

        //--------------------------------</ region:Buttons >--------------------------

        #endregion  /Buttons

 

 

 

 

        #region Methods

        //--------------------------------< region Methods >--------------------------

        private void load_List()

        {

            //--------------< load_List() >-------------

            string cn_string = Properties.Settings.Default.dbCarsConnectionString;

 

            //-< Database >

            SqlConnection cn_connection = new SqlConnection(cn_string);

            if (cn_connection.State != ConnectionState.Open) cn_connection.Open();

 

            string sql_Text = "SELECT * FROM tbl_Cars";

           

            DataTable tbl = new DataTable();

            SqlDataAdapter adapter = new SqlDataAdapter(sql_Text, cn_connection);

            adapter.Fill(tbl);

            //-</ Database >

 

 

            //< show >

            lstCars.DisplayMember = "Car";

            lstCars.ValueMember = "IDCar";

 

            lstCars.DataSource = tbl;

            //</ show >

            //--------------</ load_List() >-------------

        }

 

        private void add_Entry_to_Database()

        {

            //--------------< add_Entry_to_Database() >-------------

            string cn_string = Properties.Settings.Default.dbCarsConnectionString;

 

            //-< Database >

            SqlConnection cn_connection = new SqlConnection(cn_string);

            if (cn_connection.State != ConnectionState.Open) cn_connection.Open();

 

 

            string sNew_Car = tbxInput.Text;

       

            string sql_Text = "INSERT INTO tbl_Cars ([Car]) VALUES('" + sNew_Car + "')";

 

            SqlCommand cmd_Command = new SqlCommand(sql_Text, cn_connection);

            cmd_Command.ExecuteNonQuery();

            //-</ Database >

 

 

            //< reload >

            load_List();

            //</ reload >

            //--------------</ add_Entry_to_Database() >-------------

        }

 

        private void delete_Row_of_Database()

        {

            //--------------< delete_Row_of_Database() >-------------

            string cn_string = Properties.Settings.Default.dbCarsConnectionString;

 

            //-< Database >

            SqlConnection cn_connection = new SqlConnection(cn_string);

            if (cn_connection.State != ConnectionState.Open) cn_connection.Open();

 

            DataRowView row = lstCars.SelectedItem as DataRowView;

            string IDCar = row["IDCar"].ToString();

            string sql_Text = "DELETE FROM tbl_Cars WHERE(IDCar = " + IDCar + ")";

 

            SqlCommand cmd_Command = new SqlCommand(sql_Text, cn_connection);

            cmd_Command.ExecuteNonQuery();

            //-</ Database >

 

 

            //< reload >

            load_List();

            //</ reload >

            //--------------</ delete_Row_of_Database() >-------------

        }

 

        private void update_Entry_in_Database()

        {

            //--------------< update_Entry_in_Database() >-------------

            string cn_string = Properties.Settings.Default.dbCarsConnectionString;

 

            //-< Database >

            SqlConnection cn_connection = new SqlConnection(cn_string);

            if (cn_connection.State != ConnectionState.Open) cn_connection.Open();

 

            DataRowView row = lstCars.SelectedItem as DataRowView;

            string IDCar = row["IDCar"].ToString();

            string sql_Text = "UPDATE tbl_Cars SET [Car] = '" + tbxInput.Text + "' WHERE IDCar = " + IDCar;

 

 

            SqlCommand cmd_Command = new SqlCommand(sql_Text, cn_connection);

            cmd_Command.ExecuteNonQuery();

            //-</ Database >

 

 

            //< reload >

            load_List();

            //</ reload >

            //--------------</ update_Entry_in_Database() >-------------

        }

 

        //--------------------------------</ region Methods >--------------------------

        #endregion /Methods

 

 

 

        private void lstCars_SelectedIndexChanged(object sender, EventArgs e)

        {

            DataRowView row = lstCars.SelectedItem as DataRowView;

            tbxInput.Text  = row["Car"].ToString();

        }

    }

}

 

 

 

Connectionstring

Die Connection underr app.config

 

XML Code under app.config

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

    <configSections>

    </configSections>

    <connectionStrings>

        <add name="dbTest03.Properties.Settings.dbCarsConnectionString"

            connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\dbCars.mdf;Integrated Security=True"

            providerName="System.Data.SqlClient" />

    </connectionStrings>

    <startup>

        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />

    </startup>

</configuration>

 

 

 

Form1

Form1.Designer Code

namespace dbTest03

{

    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.lstCars = new System.Windows.Forms.ListBox();

            this.lblCars = new System.Windows.Forms.Label();

            this.tbxInput = new System.Windows.Forms.TextBox();

            this.btnAdd = new System.Windows.Forms.Button();

            this.btnDelete = new System.Windows.Forms.Button();

            this.btnUpdate = new System.Windows.Forms.Button();

            this.SuspendLayout();

            //

            // lstCars

            //

            this.lstCars.FormattingEnabled = true;

            this.lstCars.ItemHeight = 16;

            this.lstCars.Location = new System.Drawing.Point(21, 77);

            this.lstCars.Name = "lstCars";

            this.lstCars.Size = new System.Drawing.Size(200, 244);

            this.lstCars.TabIndex = 0;

            this.lstCars.SelectedIndexChanged += new System.EventHandler(this.lstCars_SelectedIndexChanged);

            //

            // lblCars

            //

            this.lblCars.AutoSize = true;

            this.lblCars.Location = new System.Drawing.Point(19, 19);

            this.lblCars.Name = "lblCars";

            this.lblCars.Size = new System.Drawing.Size(102, 17);

            this.lblCars.TabIndex = 1;

            this.lblCars.Text = "Database Cars";

            //

            // tbxInput

            //

            this.tbxInput.Location = new System.Drawing.Point(237, 25);

            this.tbxInput.Name = "tbxInput";

            this.tbxInput.Size = new System.Drawing.Size(133, 22);

            this.tbxInput.TabIndex = 2;

            //

            // btnAdd

            //

            this.btnAdd.Location = new System.Drawing.Point(237, 77);

            this.btnAdd.Name = "btnAdd";

            this.btnAdd.Size = new System.Drawing.Size(133, 47);

            this.btnAdd.TabIndex = 3;

            this.btnAdd.Text = "Add";

            this.btnAdd.UseVisualStyleBackColor = true;

            this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);

            //

            // btnDelete

            //

            this.btnDelete.Location = new System.Drawing.Point(237, 130);

            this.btnDelete.Name = "btnDelete";

            this.btnDelete.Size = new System.Drawing.Size(133, 47);

            this.btnDelete.TabIndex = 3;

            this.btnDelete.Text = "Delete";

            this.btnDelete.UseVisualStyleBackColor = true;

            this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);

            //

            // btnUpdate

            //

            this.btnUpdate.Location = new System.Drawing.Point(237, 183);

            this.btnUpdate.Name = "btnUpdate";

            this.btnUpdate.Size = new System.Drawing.Size(133, 47);

            this.btnUpdate.TabIndex = 3;

            this.btnUpdate.Text = "Update";

            this.btnUpdate.UseVisualStyleBackColor = true;

            this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click);

            //

            // Form1

            //

            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);

            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

            this.ClientSize = new System.Drawing.Size(393, 393);

            this.Controls.Add(this.btnUpdate);

            this.Controls.Add(this.btnDelete);

            this.Controls.Add(this.btnAdd);

            this.Controls.Add(this.tbxInput);

            this.Controls.Add(this.lblCars);

            this.Controls.Add(this.lstCars);

            this.Name = "Form1";

            this.Text = "Form1";

            this.Load += new System.EventHandler(this.Form1_Load);

            this.ResumeLayout(false);

            this.PerformLayout();

 

        }

 

        #endregion

 

        private System.Windows.Forms.ListBox lstCars;

        private System.Windows.Forms.Label lblCars;

        private System.Windows.Forms.TextBox tbxInput;

        private System.Windows.Forms.Button btnAdd;

        private System.Windows.Forms.Button btnDelete;

        private System.Windows.Forms.Button btnUpdate;

    }

}

 

 

 

Mobile
»
Winforms: Local Database create, bind, show SELECT INSERT UPDATE DELETE
»
WPF control in a Windows Forms application
»
Wie öffnet man in C# WinForms ein zweites Formular?
»
Wie kopiert man ein Formular in Microsoft Winforms

.

Contact for Jobs, Project Requests: raimund.popp@microsoft-programmierer.de