WHAT'S NEW?
Loading...
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
The following source code performs CRUD operation using C# programming language. In addition, search function also added in this source code.

This code used for my future reference. I hope it could be helpful also. Thank you



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.OleDb;
namespace CRUD_Application_CSharp
{
    public partial class Form1 : Form
    {
        String connectionString;
        OleDbConnection conn;
        OleDbDataAdapter da;
        OleDbCommand cmd;
        //DataSet ds;
        string sql;
        public int x;

        public Form1()
        {
            InitializeComponent();
        }
        public void dbConnection()
        {

            connectionString = @"Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\\Users\Juno\Documents\dbInformation.mdb";
            conn = new OleDbConnection(connectionString);
            conn.Open();
            //MessageBox.Show("Connection Open  !");
            //conn.Close();
        }

        private void btnReadDatabase_Click(object sender, EventArgs e)
        {
     
            retrieveALL();

        }
        private void retrieveALL(){
             dbConnection();
            sql = "SELECT * FROM tblProfile";
            da = new OleDbDataAdapter(sql, conn);
            DataTable dt = new DataTable();      //ds = new DataSet();
            da.Fill(dt);                         //da.Fill(ds, "dbInformation");
            dataGridView1.DataSource = dt;       //dataGridView1.DataSource = ds.Tables[0];
            conn.Close();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {

            dbConnection();
            sql = "INSERT INTO tblProfile (Firstname,Lastname,Gender) VALUES ('" + txtFname.Text + "','" + txtLname.Text + "','" + cbGender.Text + "')";
            cmd = new OleDbCommand(sql, conn);
            cmd.ExecuteNonQuery();
            MessageBox.Show("Successfully Added to your Database", "New Record Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
            conn.Close();

            //btnReadDatabase_Click(sender, e);
            retrieveALL();
        }
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
           
            x = dataGridView1.Rows.IndexOf(dataGridView1.CurrentRow);

            txtFname.Text = dataGridView1.Rows[x].Cells[1].Value.ToString();
            txtLname.Text = dataGridView1.Rows[x].Cells[2].Value.ToString();
            cbGender.Text = dataGridView1.Rows[x].Cells[3].Value.ToString();
            MessageBox.Show(dataGridView1.Rows[x].Cells[0].Value.ToString());

        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            dbConnection();
            int indexID;
            x = dataGridView1.Rows.IndexOf(dataGridView1.CurrentRow);
            indexID =  Convert.ToInt32((dataGridView1.Rows[x].Cells[0].Value.ToString()));

            sql = "UPDATE tblProfile SET Firstname= '" + txtFname.Text + "',Lastname='" + txtLname.Text +
                "',Gender='" + cbGender.Text + "' WHERE ID=" + indexID + "";

            cmd = new OleDbCommand(sql, conn);
            cmd.ExecuteNonQuery();
            MessageBox.Show("Successfully Updated...", "Update");
            conn.Close();

            //btnReadDatabase_Click(sender, e);
            retrieveALL();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            dbConnection();
            int indexID;
            x = dataGridView1.Rows.IndexOf(dataGridView1.CurrentRow);
            indexID = Convert.ToInt32((dataGridView1.Rows[x].Cells[0].Value.ToString()));

            sql = "DELETE FROM tblProfile WHERE ID=" + indexID + "";

            cmd = new OleDbCommand(sql, conn);
            cmd.ExecuteNonQuery();
            MessageBox.Show("Successfully Deleted...", "Delete");
            conn.Close();
            retrieveALL();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            dbConnection();
            sql = "SELECT * FROM tblProfile WHERE Firstname='" + txtSearch.Text+ "' OR Lastname='" + txtSearch.Text +"'";
            da = new OleDbDataAdapter(sql, conn);
            DataTable dt = new DataTable();      //ds = new DataSet();
            da.Fill(dt);                         //da.Fill(ds, "dbInformation");
            dataGridView1.DataSource = dt;       //dataGridView1.DataSource = ds.Tables[0];
            conn.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView2.Columns.Add("Firstname","fname");
            dataGridView2.Columns.Add("Lastname","lname");
            dataGridView2.Columns.Add("Gender","gender");
            retrieveALL();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtFname.Clear();
            txtLname.Clear();
            txtSearch.Clear();
            cbGender.Text = null;
        }

        private void button1_Click(object sender, EventArgs e)
        {

           
            for (int i = 0; i < dataGridView2.Rows.Count; i++)
            {
                sql = @"INSERT INTO tblProfile (Firstname,Lastname,Gender) VALUES ('"
                    + dataGridView2.Rows[i].Cells["Firstname"].Value + "',' "
                    + dataGridView2.Rows[i].Cells["Lastname"].Value + "', '"
                    + dataGridView2.Rows[i].Cells["Gender"].Value + "')";
                dbConnection();
                cmd = new OleDbCommand(sql, conn);
                cmd.ExecuteNonQuery();

                MessageBox.Show("Successfully Added to your Database", "New Record Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
                conn.Close();

                //btnReadDatabase_Click(sender, e);
                retrieveALL();
            }
        }
    }
}


In my previous tutorial which I used Windows Form Databinding in VB.NET to bind data and Customized BindingNavigator component as I used Buttons instead the default BindingNavigator component that enable you to Add, Delete, Update, Retrieve, and Search record.

Actually, it was already done this program before in VB.NET (see How to use BindingNavigator in VB.NET). As a challenge, I migrate VB.NET to C – Sharp (C#) to do this job where in the functions can perform to Add, Delete, Update, Retrieve, and Search record, and most probably all functions and design are almost identical in my previous tutorials. In fact, the code in C# not too far from the code of VB.NET.  However, there are some lines of code that you need to understand it well because of some instances. Let say, to Startup Form. Usually, in VB.NET, we go to Project MenuWindows Application Properties – and set Startup Form which form will be loaded first. In C#, to set the Startup Form you need to double click the Program.cs on your Solution Explorer. This code generated looks like this:

 static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmHome());
        }

To change the Startup Form, you only change frmHome name in which Form you want to load first. Note, the default name of every forms are Form1, Form2, Formn every time you add new Windows Form. It’s better to change the name of every Forms to make it readable and meaningful.

The experience I had while using C# is how to show Form. Before, I can’t find a solution how to work it because in VB is very simple to show Form. This is how:

 Form frm = new frmAdd();
        frm.ShowDialog();

You cannot do (Form1.ShowDialog()) like VB to show form. Instead, initialize first to enable to show other forms.

Those are among few line of codes might take to remember while working in C# if you are VB.NET programmers expertise.

Now, let’s explore the source code:

Code for Add New Entry:

private void btnsave_Click_1(object sender, EventArgs e)
{
  this.Validate();
  this.tblinfoBindingSource.EndEdit();
  this.tblinfoTableAdapter.Update(this.dbInfoDataSet.tblinfo);
  MessageBox.Show("New Records has been successfully saved", "Save Record",    
  MessageBoxButtons.OK, MessageBoxIcon.Information);
  this.tblinfoBindingSource.AddNew();
}

Code for Update Records:

private void btnupdate_Click(object sender, EventArgs e)
{
  this.Validate();
  this.tblinfoBindingSource.EndEdit();
  this.tblinfoTableAdapter.Update(this.dbInfoDataSet.tblinfo);
  MessageBox.Show("Records has been successfully updated", "Update Records",    
  MessageBoxButtons.OK, MessageBoxIcon.Information);
}

The code for Add and Update works in the same way as you have noticed.

Code for Delete Records:

private void btndelete_Click(object sender, EventArgs e)
{
     int x;
     string fname;
     string lname;

     x = this.tblinfoDataGridView.Rows.IndexOf(this.tblinfoDataGridView.CurrentRow);
     fname = this.tblinfoDataGridView.Rows[x].Cells[0].Value.ToString();
     lname = this.tblinfoDataGridView.Rows[x].Cells[1].Value.ToString();
     if (MessageBox.Show("You want to delete" + fname + " " + lname + " records?", "Confirm 
        Entry", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == 
        System.Windows.Forms.DialogResult.Yes)
     {
        this.tblinfoBindingSource.RemoveAt(this.tblinfoBindingSource.Position);
        this.tblinfoTableAdapter.Update(this.dbInfoDataSet.tblinfo);
        MessageBox.Show(fname + " " + lname + " " + "record has been successfully deleted");
     }
     else
     {
        MessageBox.Show("Cancelled","Cancelled 
        Entry",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
     }
}

Code for Retrieve Records:

  this.tblinfoTableAdapter.Fill(this.dbInfoDataSet.tblinfo);

Code for Search Records:

private void txtsearch_TextChanged(object sender, EventArgs e)
{
  this.tblinfoBindingSource.Filter = "Firstname LIKE '%" +txtsearch.Text + "%' OR Lastname 
  LIKE '%" + txtsearch.Text + "%'";
}

The screenshots are almost identical in my previous article. Download this source code hereIf you want to save more files online and share it to your friends, sign up for free.

Login System is one of the thrilling securities that the users prompt to input their username and password or even has a user level control to enable accessing their transaction locally or through online application. Most probably every account has their own access level, for instance to avoid accessing unnecessary operation, for example the admin user has an authority to access all transaction. There are different ways of coding style in logging the system, also the uses of database such as MS SQL Server, MySQL, Oracle, ODBC, or MS Access. Unfortunately, for the beginner’s we can use MS Access to login the system. However, you may also use all databases. 

Migrating Visual Basic to C Sharp (C#) unfortunately is not really hard because almost both of them has a similarities except for the advantages and disadvantages of them. If you had already a background in C, C++, or even in java is advantage. Actually, I didn’t expect knowing this language before but when I encountered it seems looks like the same in java, so I tried and I made it accidentally. Unintentionally, I made some fun making webpage and published it to my own site because I enjoy what I’m doing. So, every time I’m done making unintentional project and I think it is important, I write it for an article and post to my own site.

Making a login system is very important in small or a large system to avoid access unnecessarily transaction. This example shows a simple but it is very helpful for the beginner’s how to go through with the login system. Actually, this code written before in Visual Basic and it looks like almost same, I made some understanding how the proper syntax is being made.

This complete code written in C sharp and applied it in ASP.NET.
protected void Btnlogin_Click(object sender, EventArgs e)
    {
        //when you noticed..I split dbprovider and dbsource,
        //actually you can combined them without having
        //concatenation.
        string dbProvider = "PROVIDER = Microsoft.Jet.OLEDB.4.0;";
        string dbSource = "Data Source = C:\\account.mdb";


        OleDbConnection con = new OleDbConnection(dbProvider + dbSource);

        string sql = "SELECT * FROM tblaccount WHERE Username = '" + txtusername.Text +
            "' AND Password = '" + txtpassword.Text +
            "' AND UserLevel = '" + DropDownList1.Text + "'";

        OleDbCommand cmd = new OleDbCommand(sql, con);
        con.Open();
   
        OleDbDataReader sdr = cmd.ExecuteReader();

        string userlevel; //variable declaration for the user

        userlevel = DropDownList1.SelectedItem.Text.ToString();

      
        if (sdr.HasRows == true) //determine if the data has rows
        {
            switch (userlevel)//reads the username if it is equal to the given username
            {
                case "User"://if sprint username was input, Loginforsprint.asp web form
                    Response.Redirect("~/Loginforuser.aspx");
                    break;
                case "Admin":
                    Response.Redirect("~/Loginforadmin.aspx");
                    break;
            }
         
        }
        else
        {
                lblerror.Text = "Invalid data!!";
           
        }
     
      
    }

Hopefully this is very helpful. In fact, I’m not totally good but the above code is totally running!
I’ll show you the screenshots:
 
In order to come up with the output, you should provide 3 Web Forms for user login, login for user, and login for admin, 3 Labels for username with (Textbox), password with (Textbox), user level with (DropDownList), and 1 Button.

ASP.Net build in codes such as drag and drop from the toolbox to web form or even from the opening is complicated for the first time user. However, as we go along and focus what’s behind the code in every line it makes you think how you are going to align every label, text box, button, etc. that comes from the toolbox. There are different ways how you are going to work with, such as table. However, Cascading Style Sheet (CSS) is most interesting way to align, emphasize your text, label, background, and a lot more. Visit w3shcools.com for more information about CSS.
Now, let’s look how to align label and text box in ASP.Net using C Sharp (C#) 2010.

Open your Visual Studio 2010 – New Project >select Visual C# language > Web and choose ASP.NET Empty Web Application and name it My First Web Site.
 
Next, in your solution explore right click My First Web Site which is the name of your website and click Add new item, Select Web Form and name it Home.aspx.

Here is the code generated of your Home.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="My_First_Web_Site.Home" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    </form>
</body>
</html>
 
We are going to split. Your form looks like this.
Add the following CSS code after the </title> closing tag until closing tag </head> 

    <style type="text/css">
        .Main
        {
            background-color: white;
            margin-left: auto; /* Center mainTable for >= IE6  */
            margin-right: auto; /* Center mainTable for >= IE6  */
        }
        .LeftLabelColumn
        {
            display: block;
            margin-left: 10px;
            margin-right: 10px;
            height: 22px;
            padding-top: 5px;
        }
        .LeftValueColumn
        {
            display: block;
            margin-left: 10px;
            margin-right: 10px;
        }
    </style>

Your output looks like the following screenshots:

 
Next, we are going to delete open <div> and close </div>
 
 Delete the highlighted <div> </div> and paste this code.

<div class="Main">
    <!-- This label where my output firstname, lastname, middlename, and address are being displayed -->
        <asp:Label ID="lblshowmyname" runat="server" CssClass="LeftLabelColumn"
            Font-Size="Larger"></asp:Label>
        <div style="float: left; border-top: solid 10px white;">

            <asp:Label ID="Label1" CssClass="LeftLabelColumn" runat="server"
                Text="Firstname"></asp:Label>
            <asp:Label ID="Label2" CssClass="LeftLabelColumn" runat="server"
                Text="Lastname"></asp:Label>
            <asp:Label ID="Label3" CssClass="LeftLabelColumn" runat="server"
                Text="Middlename"></asp:Label>
            <asp:Label ID="Label4" CssClass="LeftLabelColumn" runat="server" Text="Address"></asp:Label>
        </div>
        <!-- Because we can't use border-top, margin-top or padding-top on a textbox, we surround the textboxes with div tags -->
        <div class ="LeftLabelColumn">
            <div style="padding-top: 5px;"><asp:TextBox ID="TextBox1"
                    CssClass="LeftValueColumn" runat="server"></asp:TextBox></div>
            <div style="padding-top: 5px;"><asp:TextBox ID="TextBox2"
                    CssClass="LeftValueColumn" runat="server"></asp:TextBox></div>
            <div style="padding-top: 5px;"><asp:TextBox ID="TextBox3"
                    CssClass="LeftValueColumn" runat="server"></asp:TextBox></div>
            <div style="padding-top: 5px;"><asp:TextBox ID="TextBox4"
                    CssClass="LeftValueColumn" runat="server" Width="459px"></asp:TextBox>
                <asp:Button ID="Button1" runat="server" Text="Show me"
                    onclick="Button1_Click" />
            </div>
          
        </div>
    </div>

Note: make sure paste the code above after this code <form id="form1" runat="server"> and closing </form>

After you paste the code, the final output looks like the following.
The label above displays your firstname, lastname, middlename, and address when your click Show me

Now, we are going to put code in order to display the result in the label. Double click the show me button. The code should looks like the following.
 
Copy this code:
 string fname;
        string lname;
        string mname;
        string address;

        fname = TextBox1.Text;
        lname = TextBox2.Text;
        mname = TextBox3.Text;
        address = TextBox4.Text;

        lblshowmyname.Text = "Name: " + fname + " " + mname +
            ". " + lname +  " From: " + address;

Finally, your final code looks like:
 So, now we are done! Press F5 to run your program. The output runs your browser.


That’s the final output!
Next: Creating Master Page in ASP.NET 2010