HOME
PRIVACY POLICY
ABOUT US

Simple C# sharp windows desktop software development with CRUD operation for beginners using windows form

C sharp programming for beginers CRUD Operation | DEEP LEARNING ( AI ) FOR BEGINNERS AND CODERS | MULTIPLEWORDS BY PROGRAMMERS

In this article we will be discussing how to develop softwares for windows desktop application using .net Form technologies using C# sharp . We will be completing task of our old student details system . If you hadn't know it . Kindly go to this link and know which task we will complete in this exmple . It Basically contains CRUD Operation

Requirements for this example


  1. Basic programming knowledge
  2. C# syntax
  3. SQL knowledge

Environment


  1. Visual studio 2017 community edition . For help you can view this article .
  2. MSSQL Server express editiom . For help you can view this article.

We can Make Desktop application using many different technologies some is by microsoft and some are by other companies also . We will be discussing one of the most popular technology used to make windows Desktop software . We will be using Windows Form technology . We will complete task of our student details system . To know more about task click here . In Windows Form Each form has two section one is designer Part and one is implementation part or some calls it back end part or code writing section .

For Creating New Project in Visual Studio you need to go the files and click on new and from there to new Project . Give Name as WindowsFormApplication . As you create project visual studio creates for you one default form name as form1.designer and its respective Code writing section name as form1.cs.

We will be Following Steps below to complete our Task

DATABASE CREATION IN SQL

1.Go to microsoft sql management studio . There you need to enter Server Name our is .\SQLExpress and click connect .

2.Create New Database

  • Right Click On databases and click on New Database . In Opened windows you need to give database name in your case it is StudentsDB and then Click Ok . New Database Will be created

3 Create Table

a.Create New Table By designing

  • Now will see our create database in the list of databases . There you need to go our newly create database inside that database we have tables section .
  • In Tables Section right click and select New table it will open window . In opened window you need to enter fields name with its datatype . and click (ctrl + S) to save that table and give name as student_table

b.Create Table by SQL Query

  • you can create table through query also . Just right click database and select New query it will open window you can paste following code to it and click on execute button to it .



DESIGNING OF WINDOWS FORM IN VISUAL STUDIO


1.We will Design our application how user will look it. For designing part we will be using forms default toolbox and using drag and drop functionality of designer to place different component to the screen . We will placing labels and Textbox and Buttons for inputs and dataGridView for viewing already entered students in the database .


2.After you Placed all components properly in the screen . You need to provides its Name and Text to labels and Textbox so that you can access those component behind code in form1.cs to populate and Manipulate through programming .

  • To Give text to label you need to left click on that component and click properties which will on left side of screen . There you have to find Text and change it according to you .
  • We will give Labels text as Name,Address,Telephone,Standard and Roll Number
  • Than we will give Name to each Textbox same manner as above only now we will change Name in properties of component
  • We will give Name as NameTextBox, TelephoneTextBox ,AddressTextBox , StandardTextBox , RollnumberTextBox

3.Then we will assigning Events to component . Events means handling user interaction with our software

  • We will be Assigning Events to Button as click Event . By just going to properties and in properties click on power type icon above and then on click Text . Double click there . Visual Studio automatically creates event for you in form1.css and opens it for you

4.Then we will configure datagridview

  • First of all drag and drop datagridview to the screen and adjust its properly
  • Assign data source to datagridview by clicking on arrow button above .
  • It will ask you for datasource . If you dont have datasource just click on add Project Data source . And then Click on New Connection then select Microsoft Sql Server then continue. As we have made our database in MSSQL with database name studentDB . In Server Name Provide Server name . provide here as .\SQLExpress and in database select studentDB click next. Then Select Table and finish .If it is selected automatically then ok if no then go to arrow again in choose datasource select Other Datasource there in Project data source . Then StudentDBset and then inside it our table .

Following Video will demonstrate the procedure of Designing and assigning Name , Text and events to it

Code Writing Part

Code Writing part is done in form1.cs file which is under Form1 in solution Explorer Right hand side . In This part we will learn how to fetch data from the server using SQL Queries and how to manipulate data before showing to the user . In This Part we will Learn how to insert , Update and Delete Data from Database using C Form using Sql Statements and Execute it .

1.Firstly We will create function to open Connection to database . This connection will be used to execute sql query in database. For use Configuration Manager .kindly Add Reference . System.Configuration in solution Explorer.

       public SqlConnection ConnectionOpen()
        {

            string connectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApplication2.Properties.Settings.StudentsDBConnectionString"].ConnectionString;
            SqlConnection con = new SqlConnection(connectionString);
            return con;
        }

  • In above Code we have taken first connection string. Which is created in app.conf at time of datasource binding of our datagridview . You can go there and copy the connection string and paste at place of "WindowsFormsApplication2.Properties.Settings.StudentsDBConnectionString" to your connection string .

2.We will Complete Insert Task . Insert Task is accomplished when user clicks on Insert Button in the Designing . Means First you need bind click event to Insert Button . Which we have already done . Due to our above action new function is create Behind code . In That function we to write following code . Copy the below code

INSERT


if (NameTextBox.Text == "" || AddressTextBox.Text == "" || TelephoneTextBox.Text == "" || StandardTextBox.Text == "" || rollNumberTextbox.Text == "")
            {
                MessageBox.Show("Kindly Enter All fields");
               
            }
            else
            {
                try
                {
                    SqlConnection con = ConnectionOpen();
                    con.Open();

                    String selectSql = "INSERT INTO [StudentsDB].[dbo].[student_table] ([Name],[Address],[Telephone],[Standard],[Roll_Number]) VALUES 
('"+NameTextBox.Text+"','"+AddressTextBox.Text+"','"+TelephoneTextBox.Text+"','"+StandardTextBox.Text+"','"+rollNumberTextbox.Text+"')";
                   SqlCommand cmd = new SqlCommand(selectSql, con);
                    cmd.ExecuteNonQuery();
                    //  SqlDataReader r1 = cmd.ExecuteReader();
                    this.studentsDBDataSet.student_table.AcceptChanges();
                    this.student_tableTableAdapter.Fill(this.studentsDBDataSet.student_table);
                    clearTextBox();
                }
                catch (Exception p)
                {
                    MessageBox.Show(p.ToString());
                }              
             }

In the above code we have first open the sql connection and the write query in selectSql string and then initiate SqlCommand with query string and connection then execute it . We have then apply changes to datagridview by executing AcceptChanges and againing filling datagridview . ClearTextBox is function we have defined to clear all text box .


  public void clearTextBox()
        {
            NameTextBox.Text = "";
            AddressTextBox.Text = "";
            TelephoneTextBox.Text = "";
            rollNumberTextbox.Text = "";
            StandardTextBox.Text = "";
            student_id = "";
        }

Then We will write event Selection Change in datagridView to select particular record to Update


private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            int selectedrowindex = dataGridView1.SelectedCells[0].RowIndex;

            DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];
            if (selectedRow != null)
            {
                NameTextBox.Text = this.studentsDBDataSet.student_table[selectedrowindex].Name.ToString();
               AddressTextBox.Text = this.studentsDBDataSet.student_table[selectedrowindex].Address.ToString();
                TelephoneTextBox.Text = this.studentsDBDataSet.student_table[selectedrowindex].Telephone.ToString();
                rollNumberTextbox.Text = this.studentsDBDataSet.student_table[selectedrowindex].Roll_Number.ToString();
                StandardTextBox.Text = this.studentsDBDataSet.student_table[selectedrowindex].Standard.ToString();
                student_id = this.studentsDBDataSet.student_table[selectedrowindex].student_id.ToString();
            }
        }

Above We have First we have taken selected row Index which is selected . Then we have taken all information from dataset to different fields through field name and assign studend_id which variable we create . And which we will use to update database records .

UPDATE

3.To Complete UPDATE task . First we have to select row which we want to update . After that we will click update . Update code is given below


  if (NameTextBox.Text == "" || AddressTextBox.Text == "" || TelephoneTextBox.Text == "" || StandardTextBox.Text == "" || rollNumberTextbox.Text == "")
            {
                MessageBox.Show("Kindly Enter All fields");

            }
            else
            {
                try
                {
                    SqlConnection con = ConnectionOpen();
                    con.Open();

                    String selectSql = "UPDATE student_table SET Name='" + NameTextBox.Text + "',Address='" + AddressTextBox.Text + "',Telephone='" + TelephoneTextBox.Text + "',Standard='" +
 StandardTextBox.Text + "',Roll_Number='" + rollNumberTextbox.Text + "'  WHERE student_id='"+student_id+"'";
                    SqlCommand cmd = new SqlCommand(selectSql, con);
                    cmd.ExecuteNonQuery();
                    //  SqlDataReader r1 = cmd.ExecuteReader();
                    this.studentsDBDataSet.student_table.AcceptChanges();
                    this.student_tableTableAdapter.Fill(this.studentsDBDataSet.student_table);
                    clearTextBox();
                }
                catch (Exception p)
                {
                    MessageBox.Show(p.ToString());
                }
            }

We have done same things as above in Insert Just Changes SQL Statement

DELETE

To Delete a record you need to first select that record and then click delete button to delete that record .

 if (student_id== "")
            {
                MessageBox.Show("Kindly Select Rows from to delete ?");

            }
            else
            {
                try
                {
                    SqlConnection con = ConnectionOpen();
                    con.Open();

                    String selectSql = "DELETE FROM [StudentsDB].[dbo].[student_table]  WHERE student_id='" + student_id + "'";
                    SqlCommand cmd = new SqlCommand(selectSql, con);
                    cmd.ExecuteNonQuery();
                    //  SqlDataReader r1 = cmd.ExecuteReader();
                    this.studentsDBDataSet.student_table.AcceptChanges();
                    this.student_tableTableAdapter.Fill(this.studentsDBDataSet.student_table);
                    clearTextBox();
                }
                catch (Exception p)
                {
                    MessageBox.Show(p.ToString());
                }


Full Code is Given below . Kindly not forget to change equivalents Name you have given.

For more Queries and Question kindly post on Facebook group

Want to know more about me .click here

Taher Deep learning Engineer

Related Posts

GeekGuy :- October 30, 2019

https://www.youtube.com/watch?v=U7z5wLX7K_0