Support us on YouTube by Subscribing our YouTube Channel. Click here to Subscribe our YouTube Channel

Tuesday, 27 January 2015

Insert, Update and Delete Record in DataGridView C#

In this Article, we will learn How to Insert, Update and Delete Record in DataGridView in C# Windows Form Application. In Previous Post, we saw How to Create a simple Windows Form Login Application in C#.

Let's Begin:
1. Create a new Windows Form Application.
2. Create a Database (named as Sample). Add a Table tbl_Record. The following is the table schema for creating tbl_Record.
3. Create a form(named frmMain) and Drop Label, TextBox, Button and DataGridView control from  the ToolBox.
Now, Go to frmMain.cs code and add System.Data and System.Data.SqlClient namespace.
frmMain.cs Code:
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace InsertUpdateDeleteDemo
{
    public partial class frmMain : Form
    {
        SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
        SqlCommand cmd;
        SqlDataAdapter adapt;
        //ID variable used in Updating and Deleting Record
        int ID = 0;
        public frmMain()
        {
            InitializeComponent();
            DisplayData();
        }
        //Insert Data
        private void btn_Insert_Click(object sender, EventArgs e)
        {
            if (txt_Name.Text != "" && txt_State.Text != "")
            {
                cmd = new SqlCommand("insert into tbl_Record(Name,State) values(@name,@state)", con);
                con.Open();
                cmd.Parameters.AddWithValue("@name", txt_Name.Text);
                cmd.Parameters.AddWithValue("@state", txt_State.Text);
                cmd.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("Record Inserted Successfully");
                DisplayData();
                ClearData();
            }
            else
            {
                MessageBox.Show("Please Provide Details!");
            }
        }
        //Display Data in DataGridView
        private void DisplayData()
        {
            con.Open();
            DataTable dt=new DataTable();
            adapt=new SqlDataAdapter("select * from tbl_Record",con);
            adapt.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
        }
        //Clear Data
        private void ClearData()
        {
            txt_Name.Text = "";
            txt_State.Text = "";
            ID = 0;
        }
        //dataGridView1 RowHeaderMouseClick Event
        private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
            txt_Name.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
            txt_State.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
        }
        //Update Record
        private void btn_Update_Click(object sender, EventArgs e)
        {
            if (txt_Name.Text != "" && txt_State.Text != "")
            {
                cmd = new SqlCommand("update tbl_Record set Name=@name,State=@state where ID=@id", con);
                con.Open();
                cmd.Parameters.AddWithValue("@id", ID);
                cmd.Parameters.AddWithValue("@name", txt_Name.Text);
                cmd.Parameters.AddWithValue("@state", txt_State.Text);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Record Updated Successfully");
                con.Close();
                DisplayData();
                ClearData();
            }
            else
            {
                MessageBox.Show("Please Select Record to Update");
            }
        }
        //Delete Record
        private void btn_Delete_Click(object sender, EventArgs e)
        {
            if(ID!=0)
            {
                cmd = new SqlCommand("delete tbl_Record where ID=@id",con);
                con.Open();
                cmd.Parameters.AddWithValue("@id",ID);
                cmd.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("Record Deleted Successfully!");
                DisplayData();
                ClearData();
            }
            else
            {
                MessageBox.Show("Please Select Record to Delete");
            }
        }
    }
}
In the above code, I have created dataGridView1_RowHeaderMouseClick Event for updating and deleting the selected Record. When user click on the Row Header of any row then data present in the cell of the row is stored into the TextBoxes. DisplayData() method used to fill data in DataGridView. Clear() method clears the data present TextBox as well as in ID(int) variable.
Final Preview:
Hope you like it. Thanks.
[Download Source Code via Google Drive]

Tuesday, 20 January 2015

How to add AJAX Control Toolkit in Visual Studio

In this Post, we will learn How to add Ajax Control Toolkit in Visual Studio (step by step.)

Let's Begin:
1. Visit https://ajaxcontroltoolkit.codeplex.com. Click on Download button to download the latest release of AJAX Control Toolkit.
or Click on Downloads link in the menu and Select the Ajax Control Toolkit release according to your need. On clicking, AJAX Control Toolkit starts downloading.
2. Extract the downloaded file (I have extracted the file in C:\ Drive).
3. Open Visual Studio, Right Click in ToolBox and then click on Add Tab.
Provide a name to the tab so that you can find these controls easily. I have named it as AJAX Control Toolkit.
4. Expand the Tab which we have created in the previous step and Right click in it. Click on Choose Items.
5. Click on the Browse button in Choose Toolbox items and go to the location where you have extracted the ajaxcontroltoolkit.
Select AjaxControltoolkit.dll and then click on Open button.
6. After clicking on the Open button, Visual Studio displays a security warning. Click on Yes.
All the controls present in AJAXControlToolkit.dll will be displayed. Click on OK.
That's all. Now you will see all the controls present in AJAX Control Toolkit added under AJAC Control Toolkit tab in the ToolBox.
Hope you like it. Thanks.

Friday, 16 January 2015

Simple Windows Form Login Application in C#

In this Post, we will learn how to create a Simple Windows form Login application.

Let’s Begin:
1. Create a New Windows Form Application.
Create Windows Form Application
2. Add New Database (I have created a database named as MyDatabase.mdf). Add a table (named as tbl_Login). The following is the table schema for creating tbl_Login.
Table Structure
3. Create a form (frmLogin) and add Label, TextBox and button control from the Toolbox.
Login Form
4. Add another Windows Form and named it as frmMain. This form will be shown to the user after successful Login by the user.
Main Form
Now, Go to frmLogin.cs code and add System.Data and System.Data.SqlClient namespace. Double click on btn_Submit to create btn_Submit Click event.
frmLogin.cs Code:
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace LoginApplication
{
    public partial class frmLogin : Form
    {
        public frmLogin()
        {
            InitializeComponent();
        }
        //Connection String
        string cs = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True;";
        //btn_Submit Click event
        private void button1_Click(object sender, EventArgs e)
        {
            if(txt_UserName.Text=="" || txt_Password.Text=="")
            {
                MessageBox.Show("Please provide UserName and Password");
                return;
            }
            try
            {
                //Create SqlConnection
                SqlConnection con = new SqlConnection(cs);
                SqlCommand cmd = new SqlCommand("Select * from tbl_Login where UserName=@username and Password=@password",con);
                cmd.Parameters.AddWithValue("@username",txt_UserName.Text);
                cmd.Parameters.AddWithValue("@password", txt_Password.Text);
                con.Open();
                SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adapt.Fill(ds);
                con.Close();
                int count = ds.Tables[0].Rows.Count;
                //If count is equal to 1, than show frmMain form
                if (count == 1)
                {
                    MessageBox.Show("Login Successful!");
                    this.Hide();
                    frmMain fm = new frmMain();
                    fm.Show();
                }
                else
                {
                    MessageBox.Show("Login Failed!");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
After that, go to frmMain.cs form and create btn_LogOut click event. On clicking the Logout button, frmMain form hides and show frmLogin form.

frmMain.cs Code:
using System;
using System.Windows.Forms;

namespace LoginApplication
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }
        //btn_LogOut Click Event
        private void btn_LogOut_Click(object sender, EventArgs e)
        {
            this.Hide();
            frmLogin fl = new frmLogin();
            fl.Show();
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

    }
}
Final Preview:
Windows form login application
Hope you like it. Thanks.
[Download Source Code via Google Drive]

Tuesday, 13 January 2015

Pass data from one activity to another using Intent in Xamarin

In this Article, we will see how to pass data from one activity to another using Intent in Xamarin. In my previous Article, we learnt about Checkbox widget in Xamarin.

Let's Begin:
1. Create a new Android Application.
2. Add a layout (named as Main.axml).
3) Drop TextView, EditText(set id="@+id/txt_Name") and Button(set id="@+id/btn_Submit" and text="Submit") control onto the Main.axml Layout.
4) Add another Layout and name it as Result.axml.
Drop TextView(Large) control on Result.axml layout and set id="@+id/txt_Result".
Activity1.cs Code:
using System;

using Android.App;
using Android.Content;
using Android.Widget;
using Android.OS;

namespace IntentDemo
{
    [Activity(Label = "IntentDemo", MainLauncher = true, Icon = "@drawable/icon")]
    public class Activity1 : Activity
    {
        EditText txt_Name;
        Button btn_Submit;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            //Get txt_Name and btn_Submit Button CheckBox control from the Main.xaml Layout. 
            txt_Name = FindViewById<EditText>(Resource.Id.txt_Name);
            btn_Submit = FindViewById<Button>(Resource.Id.btn_Submit);
            //btn_Submit click event
            btn_Submit.Click += btn_Submit_Click;
        }

        void btn_Submit_Click(object sender, EventArgs e)
        {
            //if EditText in not Empty
            if(txt_Name.Text!="")
            {
                //passing the Activity2 in Intent
                Intent i = new Intent(this,typeof(Activity2));
                //Add PutExtra method data to intent.
                i.PutExtra("Name",txt_Name.Text.ToString());
                //StartActivity
                StartActivity(i);
            }
            else
            {
                Toast.MakeText(this,"Please Provide Name",ToastLength.Short).Show();
            }
        }
    }
}
In above Code, We have created an Intent and Bind Activity2 to it. PutExtra method of Intent allows us to store data in Key-Value pairs. We can retrieve the data in the other Activity using Intent. GetTypeExtra method. In above Code, We have passed string using PutExtra() method and for Retrieving the string in another activity, we use Intent.GetStringExtra("Name") method and pass key value in it as a parameter.
Activity2.cs Code:
using Android.App;
using Android.Content;
using Android.OS;
using Android.Widget;

namespace IntentDemo
{
    [Activity(Label = "Result")]
    public class Activity2 : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            // Set our view from the "Result" layout resource
            SetContentView(Resource.Layout.Result);
            //Get txt_Result TextView control from the Main.xaml Layout. 
            TextView txt_Result = FindViewById<TextView>(Resource.Id.txt_Result);
            //Retrieve the data using Intent.GetStringExtra method
            string name = Intent.GetStringExtra("Name");
            txt_Result.Text ="Hello, "+name;
        }
    }
}
Final Preview:
Hope you like it. Thanks.
[Download Source Code via Google Drive]

Subscribe us on YouTube

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Like us on Facebook

Blog Archive