Thursday, 11 August 2016

CRUD operation of Dropdownlist inside Gridview in asp.net


In this tutorial I’ll show you how to use dropdown list inside Gridview, and how to make edit, update, and delete operation on each field along with dropdown list. 




INITIAL CHAMBER:


Step1) Open Your Visual Studio 2010 and Create an Empty Website, Give a suitable name [gridview_demo].

Step2) In Solution Explorer you get your empty website, Add a web form, SQL Database. By going like this –

For Web Form:
gridview_demo (Your Empty Website) -> Right Click -> Add New Item -> Web Form. Name it as ->gridview_demo.aspx.


For SQL Server Database:
gridview_demo (Your Empty Website) -> Right Click -> Add New Item -> SQL Server Database. [Add Database inside the App_Data_folder].




DATABASE CHAMBER:

Step3)  Get to your Database [Database.mdf], we will create a table - -> tbl_Data, Go to the database.mdf - -> Table - -> Add New table, design your table like this:

Table - -> tbl_data [Don’t forget to make ID - -> Identity Specification - -> Yes]


C:\Users\Nilesh\Desktop\tbl_data.jpg






DESIGN CHAMBER:


Step5)  Now Open your gridview_demo.aspx file, where we create our design for binding and making edit, delete, and update operation with dropdownlist.

Gridview_demo.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>
   
       <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
           AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" DataKeyNames="id"
           onrowcancelingedit="GridView1_RowCancelingEdit"
           onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
           onrowupdating="GridView1_RowUpdating" BackColor="White"
           BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="3"
           CellSpacing="1" GridLines="None">
           <Columns>
               <asp:TemplateField HeaderText="Name">
                   <EditItemTemplate>
                       <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
                   </EditItemTemplate>
                   <ItemTemplate>
                       <asp:Label ID="Label2" runat="server" Text='<%# Bind("name") %>'></asp:Label>
                   </ItemTemplate>
               </asp:TemplateField>
               <asp:TemplateField HeaderText="Email">
                   <EditItemTemplate>
                       <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("email") %>'></asp:TextBox>
                   </EditItemTemplate>
                   <ItemTemplate>
                       <asp:Label ID="Label3" runat="server" Text='<%# Bind("email") %>'></asp:Label>
                   </ItemTemplate>
               </asp:TemplateField>
               <asp:TemplateField HeaderText="Gender">
                   <EditItemTemplate>
                       <asp:DropDownList ID="DropDownList2"  runat="server"
                           SelectedValue='<%# Bind("gender") %>'>
                           <asp:ListItem>--Select Gender--</asp:ListItem>
                           <asp:ListItem>Male</asp:ListItem>
                           <asp:ListItem>Female</asp:ListItem>
                       </asp:DropDownList>
                   </EditItemTemplate>
                   <ItemTemplate>
                       <asp:Label ID="Label4" runat="server" Text='<%# Bind("gender") %>'></asp:Label>
                   </ItemTemplate>
               </asp:TemplateField>
           </Columns>
           <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
           <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
           <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
           <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
           <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
           <SortedAscendingCellStyle BackColor="#F1F1F1" />
           <SortedAscendingHeaderStyle BackColor="#594B9C" />
           <SortedDescendingCellStyle BackColor="#CAC9C9" />
           <SortedDescendingHeaderStyle BackColor="#33276A" />
       </asp:GridView>
   
   </div>
   </form>
</body>
</html>


Your design look like this:


C:\Users\Nilesh\Desktop\gridview_demo.aspx.jpg




You have to look around this Property in Gridview:

  1. DataKeysName: id
  2. Auto Generate Delete Button: True
  3. Auto Generate Edit Button : True

In Events: [Make Double Click in each events shown below to go to the code]

  1. Row Canceling Edit
  2. Row Deleting
  3. Row Editing
  4. Row Updating


C:\Users\Nilesh\Desktop\Properties_gridview.jpg



CODE CHAMBER:

Step6) Open your gridview_demo.aspx.cs and write some code so that our application get work.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
   SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
   protected void Page_Load(object sender, EventArgs e)
   {

       if (!Page.IsPostBack)
       {
           refreshdata();
       }

   }

   public void refreshdata()
   {   
       SqlCommand cmd = new SqlCommand("select * from tbl_data", con);
       SqlDataAdapter sda = new SqlDataAdapter(cmd);
       DataTable dt = new DataTable();
       sda.Fill(dt);
       GridView1.DataSource = dt;
       GridView1.DataBind();

   }
   protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
   {
       GridView1.EditIndex = e.NewEditIndex;
       refreshdata();
   }
   protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
   {
       int id = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());
       SqlCommand cmd = new SqlCommand("delete from tbl_data where id = @id", con);
       cmd.Parameters.AddWithValue("@id", id);
       con.Open();
       cmd.ExecuteNonQuery();
       con.Close();
       refreshdata();

   }
   protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
   {
       GridView1.EditIndex = -1;
       refreshdata();
   }
   protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
   {
       int id = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());
       TextBox txtname = GridView1.Rows[e.RowIndex].FindControl("TextBox2") as TextBox;
       TextBox txtemail = GridView1.Rows[e.RowIndex].FindControl("TextBox3") as TextBox;
       DropDownList drpgender = GridView1.Rows[e.RowIndex].FindControl("DropDownList2") as DropDownList;
     
       SqlCommand cmd = new SqlCommand("update tbl_data set name=@name, email=@email,gender=@gender where id =@id", con);
       cmd.Parameters.AddWithValue("@name", txtname.Text);
       cmd.Parameters.AddWithValue("@email", txtemail.Text);
       cmd.Parameters.AddWithValue("@gender", drpgender.SelectedItem.Text);
       cmd.Parameters.AddWithValue("@id", id);
       con.Open();
       cmd.ExecuteNonQuery();
       con.Close();
       refreshdata();

     
         

   }
   
}



OUTPUT CHAMBER:

C:\Users\Nilesh\Desktop\output of gridview_demo.jpg



Update:

C:\Users\Nilesh\Desktop\Update.jpg


C:\Users\Nilesh\Desktop\Update.jpg


Show table Data:

C:\Users\Nilesh\Desktop\show table data.jpg



Hope you like it. All controls are working, you can check out, Thank you for Reading, have a good day.

1 comment:

  1. not working and its copied file in https://www.c-sharpcorner.com/UploadFile/009464/crud-operation-of-dropdownlist-inside-gridview-in-Asp-Net/

    ReplyDelete