Tuesday, June 14, 2016

Windows Form Application: Insertion, Updation and Deletion in DataGridView


Before using the following steps ensure that you have crated a table. Let the table be Sampletable with attributes Id, Name and State. The attribute Id can be set to auto increment so that the values will be incremented automatically and will serve as a primary key of your table.Enter few rows into your table.

Now, open visual studio and open a new project and then select Windows Forms application from the list. Set the name and location of your project as required. See the figure below for reference.

 
Reference: http://www.c-sharpcorner.com
 Create a form (sampleform)and add controls to it. Drag and drop textbox, labels, buttons and DataGridView controls from the toolbox. Name these controls as applicable.

 Two textboxes can be used because there are two attributes present in the table.( Id is ignored because it is set to auto-increment). Two labels can be used against these textboxes to increase readability. Three buttons each for insert, delete and update can be used. See the figure below.

Reference : www.c-sharpcorner.com

 Now, right click on the form and go to the code area. Add the following namespaces at the beginning of the code.(if not added previously)

 using System.Data ;
 using System.Data.SqlClient;

See the following code, This code is derived from www.c-sharpcorner.com. for more details go through the website.

CODE: 
  1. using System;  
  2. using System.Data;  
  3. using System.Windows.Forms;  
  4. using System.Data.SqlClient;    
  5. namespace InsertUpdateDeleteDemo  
  6. {  
  7.     public partial class sampleform : Form  
  8.     {  
  9.   SqlConnection con= new SqlConnection("Data Source=siyaram.;Initial Catalog=Sample;Integrated Security=true;");  
  10.    SqlCommand cmd;  
  11.    SqlDataAdapter adapt;  
  12.    //ID variable used in Updating and Deleting Record  
  13.    int ID = 0;  
  14.    public sampleform()  
  15.         {  
  16.             InitializeComponent();  
  17.             DisplayData();  
  18.         }  
  19.    //Insert Data  
  20.     private void btn_Insert_Click(object sender, EventArgs e)  
  21.         {  
  22.     if (txt_Name.Text != "" && txt_State.Text != "")  
  23.             {  
  24.     cmd = new SqlCommand("insert into sampletable   
  25.              (Name,State) values(@name,@state)", con);  
  26.      con.Open();  
  27.     cmd.Parameters.AddWithValue("@name", txt_Name.Text);  
  28.     cmd.Parameters.AddWithValue("@state", txt_State.Text);  
  29.     cmd.ExecuteNonQuery();  
  30.     con.Close();  
  31.     MessageBox.Show("Record Inserted Successfully");  
  32.     DisplayData();  
  33.     ClearData();  
  34.          }  
  35.     else  
  36.             {  
  37.                 MessageBox.Show("Please fill Name and State");  
  38.             }  
  39.         }  
  40.       //Display Data in DataGridView  
  41.     private void DisplayData()  
  42.         {  
  43.     con.Open();  
  44.     DataTable dt=new DataTable();  
  45.     adapt=new SqlDataAdapter("select * from sampletable",con);  
  46.     adapt.Fill(dt);  
  47.     dataGridView1.DataSource = dt;  
  48.     con.Close();  
  49.         }  
  50.      //Clear Data  
  51.     private void ClearData()  
  52.         {  
  53.    txt_Name.Text = "";  
  54.    txt_State.Text = "";  
  55.    ID = 0;  
  56.         }  
  57.     //dataGridView1 RowHeaderMouseClick Event  
  58.         private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)  
  59.         {  
  60.             ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());  
  61.             txt_Name.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();  
  62.             txt_State.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();  
  63.         }  
  64.     //Update Record  
  65.    private void btn_Update_Click(object sender, EventArgs e)  
  66.         {  
  67.     if (txt_Name.Text != "" && txt_State.Text != "")  
  68.             {  
  69.  cmd = new SqlCommand("update sampletable set Name=@name,State=@state where ID=@id", con);  
  70.                 con.Open();  
  71.                 cmd.Parameters.AddWithValue("@id", ID);  
  72.                 cmd.Parameters.AddWithValue("@name", txt_Name.Text);  
  73.                 cmd.Parameters.AddWithValue("@state", txt_State.Text);  
  74.                 cmd.ExecuteNonQuery();  
  75.                 MessageBox.Show("Record Updated Successfully");  
  76.                 con.Close();  
  77.                 DisplayData();  
  78.                 ClearData();  
  79.             }  
  80.             else  
  81.             {  
  82.                 MessageBox.Show("Please Select Record to Update");  
  83.             }  
  84.         }  
  85.      //Delete Record  
  86.    private void btn_Delete_Click(object sender, EventArgs e)  
  87.         {  
  88.     if(ID!=0)  
  89.             {  
  90.    cmd = new SqlCommand("delete sampletable   where ID=@id",con);  
  91.    con.Open();  
  92.    cmd.Parameters.AddWithValue("@id",ID);  
  93.    cmd.ExecuteNonQuery();  
  94.    con.Close();  
  95.    MessageBox.Show("Record Deleted Successfully!");  
  96.    DisplayData();  
  97.    ClearData();  
  98.             }  
  99.    else  
  100.             {  
  101.    MessageBox.Show("Please Select Record to Delete");  
  102.             }  
  103.         }  
  104.     }  
  105. }

 Save your project and check the result. check all the options like insertion, deletion and updation.

Enjoy Programming.

No comments:

Post a Comment