Random Bits

Technical Log from Didik Setiawan

Simple C# CRUD Desktop App

This simple application which I built is about CRUD application using C#. In this example, that application is being used to save information that is username and IP address of user desktop computer. For beginning, create new project on Visual Studio (I use version 2008) with name InputDataApp.

inputdataapp1

Click Form1 that appears after we create new project, edit on the menu Properties > Name for coding reference and on Text for appearance description.

inputdataapp2 inputdataapp3

Add 3 label for description and 3 text box to grab user input. To do this, just do drag-and-drop on the menu Toolbox > Label and TextBox.

Tambahkan 3 label untuk keterangan dan 3 text box untuk menangkap inputan user. Caranya dengan drag-and-drop di bagian Toolbox > Label dan TextBox. This should be an example:

inputdataapp4

Edit on properties > name in existing textbos, for example textBox1 change to tboxUser to link the coding reference easier latter.

inputdataapp5

Repeat previous step for textBox2 and textBox3. Then add 4 buttons with help menu properties > button.

inputdataapp6 inputdataapp7

Edit on menu preperties from previous buttons on its Name and Text menu variable. So there are 4 name properties: btnCari, btnTambah, btnEdit and btnHapus Next step is add DataGridView form as main menu to display output from the datasource (in this case, database) in realtime.

inputdataapp8

Things to pay attention more from this DataGridView is properties on AllowUserToAddRows and AllowUserToDeleteRows which has default configuration True, must be changed to False.

inputdataapp9

After all those forms created, then dive in coding side. To do this, right click on Form1.cs and choose View Code.

inputdataapp10

Change the code as follow:

(Form1) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
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 InputDataApp
{
    public partial class InputDataForm : Form
    {
        private static string strconn = "server=.; user id = user; password = sebuahpassword; database=InputDataDB;";
        private SqlCommand cmd;
        private SqlDataReader rd;

        public InputDataForm()
        {
            InitializeComponent();
            BindGrid();
        }

        private void BindGrid()
        {
            using (SqlConnection conn = new SqlConnection(strconn))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM datakomputer", conn))
                {
                    cmd.CommandType = CommandType.Text;
                    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                    {
                        using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);
                            dataGridView1.DataSource = dt;
                        }
                    }
                }
            }
        }

        private void awal()
        {
            tboxUser.Text = "";
            tboxIP.Text = "";
            tboxKet.Text = "";
        }

        private void InputDataForm_Load(object sender, EventArgs e)
        {
            awal();
            BindGrid();
        }

        private void btnCari_Click(object sender, EventArgs e)
        {
            if (tboxUser.Text.Trim() != "")
            {
                using (SqlConnection conn = new SqlConnection(strconn))
                {
                    cmd = new SqlCommand("select * from datakomputer where NamaUser='" + tboxUser.Text + "'", conn);
                    conn.Open();
                    rd = cmd.ExecuteReader();
                    rd.Read();

                    if (rd.HasRows)
                    {
                        tboxUser.Text = rd["NamaUser"].ToString();
                        tboxIP.Text = rd["IP_Address"].ToString();
                        tboxKet.Text = rd["Deskripsi"].ToString();

                    }
                    else
                    {
                        MessageBox.Show("Data komputer tidak ditemukan", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
            }
        }

        private void btnTambah_Click(object sender, EventArgs e)
        {
            if (tboxUser.Text.Trim() == "" || tboxIP.Text.Trim() == "" || tboxKet.Text.Trim() == "")
            {
                MessageBox.Show("Data inputan belum lengkap", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                using (SqlConnection conn = new SqlConnection(strconn))
                {
                    cmd = new SqlCommand("insert into datakomputer (NamaUser,IP_Address,Deskripsi) values ('" + tboxUser.Text + "','" + tboxIP.Text + "','" + tboxKet.Text + "')", conn);
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Data berhasil disimpan", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    awal();
                    BindGrid();
                }
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (tboxUser.Text.Trim() == "" || tboxIP.Text.Trim() == "" || tboxKet.Text.Trim() == "")
            {
                MessageBox.Show("Data siswa belum lengkap", "Peringatan", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                using (SqlConnection conn = new SqlConnection(strconn))
                {
                    cmd = new SqlCommand("update datakomputer set NamaUser='" + tboxUser.Text + "', IP_Address='" + tboxIP.Text + "', Deskripsi='" + tboxKet.Text + "' where NamaUser ='" + tboxUser.Text + "'", conn);
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Data berhasil diedit", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    awal();
                    BindGrid();
                }
            }
        }

        private void btnHapus_Click(object sender, EventArgs e)
        {
            using (SqlConnection conn = new SqlConnection(strconn))
            {
                cmd = new SqlCommand("delete from datakomputer where NamaUser='" + tboxUser.Text + "'", conn);
                conn.Open();
                cmd.ExecuteNonQuery();
                MessageBox.Show("Data berhasil dihapus", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                awal();
                BindGrid();
            }
        }
    }
}

Connect those previous buttons with created code. Start from Search button. To do this, change Events Click on that form (search thunder icon on Properties):

inputdataapp11 inputdataapp12

Edit this based on code previously created. Repeat this step for all existing buttons. Next step, create database on MS SQL. In this example, I use MS SQL 2008 R2. Login to MS sQL Server Management Studio, then create this query:

inputdataapp13

Based on created code, then we need to create database with name InputDataDB. To create this, execute following command:

create database InputDataDB;

Click execute or press F5 on MS SMS. Then command for the tables:

use InputDataDB;
 
create table datakomputer
(
    NamaUser varchar(255),
    IP_Address varchar(255),
    Deskripsi varchar(255)
);

To confirm that the table successfully created, check with this query:

select * from datakomputer

Back to Visual Studio, the next step we need do is compile the code that have been built. Click Build > Build Solution (or press F6). After compilation process success, application can be run by click Debug > Start Without Debugging (or press Ctrl + F5).

inputdataapp14 inputdataapp15

inputdataapp16

That’s all. This simple application can do add, edit and delete data as user demand. To download the complete sourcecode of this application, you can go to here:

https://github.com/didiksetiawan/InputDataApp

Comments