Click here to Skip to main content
15,885,309 members
Articles / Web Development / ASP.NET

Editable Gridview with Textbox, CheckBox, Radio Button and DropDown List

Rate me:
Please Sign up or sign in to vote.
4.45/5 (29 votes)
15 Jun 2009CPOL1 min read 381.4K   17.8K   63   24
Edit Gridview that contains various ASP.NET controls

Introduction

This is an example of an editable gridview containing different ASP.NET controls. When user wants to edit values in gridview, she/he can use these controls to edit existing values in Gridview Edit Mode.

Using the Code

In my database, called “Demo1”, there is a table “employee” that has 7 fields. The table structure: 

Column Name Datatype
Emp_ID Varchar(50)
Emp_name Varchar(50)
Emp_address Varchar(50)
Department Varchar(50)
Salary Varchar(50)
Maritalstatus Varchar(50)
Active_Status Varchar(50)

Here, showgrid() function is used to populate Gridview1.

C#
  public void showgrid()
   {
   DataTable dt = new DataTable();
   sqlcon = new SqlConnection(con );
   sqlcon.Open();
   SqlDataAdapter sda = new SqlDataAdapter();
   string strQuery = "select * from employee ";
   SqlCommand cmd = new SqlCommand(strQuery);
   cmd.CommandType = CommandType.Text;
   cmd.Connection = sqlcon;
   sda.SelectCommand = cmd;
   sda.Fill(dt);
   GridView1.DataSource = dt;
   GridView1.DataBind();
   }

Now it would look as shown below:

1.JPG

Now, when user clicks on Edit Button, the gridview will be in editable mode, and it would look as shown below:

2.JPG

So, each field in a row transforms in Edit Mode, except ID Field, because it is unchangeable here. We can change Name, Address and Salary by editing respective Textbox. For Department, we can choose from Dropdown list, for Status we need to use Radio Button List and to change Active status, use Checkbox List. So, I need to change my mark up to do the same, below the complete mark up. Here I add EditItemTemplate Field containing ASP.NET Controls within TemplateField.

XML
<form id="form1" runat="server">
<div>
Sample Employee Information  
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
         onrowcancelingedit="GridView1_RowCancelingEdit" 
        onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating" 
        onrowdatabound="GridView1_RowDataBound">
                  <Columns>
           <asp:TemplateField HeaderText="ID">
           <ItemTemplate >
               <asp:Label ID="Label6" runat="server" Text='<%# Eval("emp_id") %>' >
		</asp:Label>
           </ItemTemplate>
           </asp:TemplateField>
           <asp:TemplateField HeaderText="Name">
           <ItemTemplate >
              <asp:Label runat="server" Text='<%# Eval("emp_name") %>' >
		</asp:Label>
           </ItemTemplate>
           <EditItemTemplate >
               <asp:TextBox ID="TextBox1" runat="server" Text='
			<%# Eval("emp_name")%>'  ></asp:TextBox>
           </EditItemTemplate>
               </asp:TemplateField>
           <asp:TemplateField HeaderText="Address">
           <ItemTemplate>
               <asp:Label ID="Label1" runat="server" Text='<%# Eval
				("emp_address") %>'></asp:Label>
           </ItemTemplate>
           <EditItemTemplate >
               <asp:TextBox ID="TextBox2" runat="server" Text='<%# 
				Eval("emp_address") %>' ></asp:TextBox>
           </EditItemTemplate>
           </asp:TemplateField>
           <asp:TemplateField HeaderText="Department">
           <ItemTemplate >
               <asp:Label ID="Label2" runat="server" Text='<%# Eval
				("department") %>'></asp:Label>
           </ItemTemplate>
           <EditItemTemplate >
               <asp:DropDownList ID="DropDownList1" runat="server" >
                
               </asp:DropDownList>
           </EditItemTemplate>
           </asp:TemplateField>
           <asp:TemplateField HeaderText="Salary">
           <ItemTemplate >
               <asp:Label ID="Label3" runat="server" Text='<%# Eval
					("salary") %>'></asp:Label>
           </ItemTemplate>
           <EditItemTemplate>
               <asp:TextBox ID="TextBox3" runat="server" Text='<%# 
				Eval("salary") %>' ></asp:TextBox>
           </EditItemTemplate>
           </asp:TemplateField>
               
           <asp:TemplateField HeaderText="Status">
           <ItemTemplate >
               <asp:Label ID="Label4" runat="server" Text='<%# 
			Eval("Maritalstatus") %>'></asp:Label>
           </ItemTemplate>
           <EditItemTemplate >
                <asp:RadioButtonList ID="RadioButtonList1" runat="server" >
   <asp:ListItem>Single</asp:ListItem>
   <asp:ListItem>Married</asp:ListItem>
</asp:RadioButtonList>
           </EditItemTemplate>
           </asp:TemplateField>
           <asp:TemplateField HeaderText="Active">
           <ItemTemplate >
               <asp:Label ID="Label5" runat="server" Text='<%# 
			Eval("Active_Status") %>'></asp:Label>
           </ItemTemplate>
           <EditItemTemplate >
                <asp:CheckBoxList ID="CheckBoxList2" runat="server" s>
   <asp:ListItem>Active</asp:ListItem>
</asp:CheckBoxList>
           </EditItemTemplate>
           </asp:TemplateField>
              
           <asp:TemplateField HeaderText="Edit" ShowHeader="false">
               <ItemTemplate>
                   <asp:LinkButton ID="btnedit" runat="server" 
			CommandName="Edit" Text="Edit" ></asp:LinkButton>
               </ItemTemplate>
               <EditItemTemplate>
                   <asp:LinkButton ID="btnupdate" runat="server" 
			CommandName="Update" Text="Update" ></asp:LinkButton>
                   <asp:LinkButton ID="btncancel" runat="server" 
			CommandName="Cancel" Text="Cancel"></asp:LinkButton>
               </EditItemTemplate>
            </asp:TemplateField>
       </Columns>
    </asp:GridView>
</div>   
</form>

Here, I have taken 4 Gridview Events:

C#
onrowcancelingedit="GridView1_RowCancelingEdit" 
onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating"
onrowdatabound="GridView1_RowDataBound"

First, GridView1_RowDataBound is used to populate control value from database for each of the records.

C#
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
   {
   DataRowView drv = e.Row.DataItem as DataRowView;
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
   if ((e.Row.RowState & DataControlRowState.Edit) > 0)
   {
   DropDownList dp= (DropDownList )e.Row .FindControl ("DropDownList1");
   DataTable dt = load_department();
   for (int i = 0; i < dt.Rows.Count; i++)
   {
   ListItem lt = new ListItem();
   lt.Text = dt.Rows[i][0].ToString();
   dp.Items.Add(lt);
   }
   dp.SelectedValue = drv[3].ToString();
   RadioButtonList rbtnl = (RadioButtonList)e.Row.FindControl("RadioButtonList1");
   rbtnl.SelectedValue = drv[5].ToString();
   CheckBoxList chkb = (CheckBoxList)e.Row.FindControl("CheckBoxList2");
   chkb.SelectedValue = drv[6].ToString();
}

Now, for gridview editing, GridView1_RowCancelingEdit() and GridView1_RowEditing().

C#
protected void GridView1_RowCancelingEdit
		(object sender, GridViewCancelEditEventArgs e)
   {
   GridView1.EditIndex = -1;
   showgrid();   } 
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
   {
   
   GridView1.EditIndex = e.NewEditIndex;
   showgrid();
   } 

Finally for new values updating, GridView1_RowUpdating().

C#
 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
   {
Label lb = (Label)GridView1.Rows[e.RowIndex].FindControl("Label6");
   DropDownList ddl = 
	(DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropDownList1");
   RadioButtonList rbl = 
    (RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("RadioButtonList1");
   CheckBoxList chb = 
	(CheckBoxList)GridView1.Rows[e.RowIndex].FindControl("CheckBoxList2");
   TextBox tx1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");
   TextBox tx2 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2");
   TextBox tx3 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox3");
   sqlcon = new SqlConnection(con);
   sqlcon.Open();
   string sql = "update employee set emp_name='" + 
	tx1.Text + "',emp_address='" + tx2.Text + "',salary='" +
   	tx3.Text + "',department='" + ddl.SelectedValue.ToString() 
	+ "',maritalstatus='" + rbl.SelectedValue.ToString() + "',Active_status='" 
		+ chb.SelectedValue.ToString() + "' where emp_id='" +
   lb.Text + "'";
SqlCommand cmd = new SqlCommand(sql);
   cmd.CommandType = CommandType.Text;
   cmd.Connection = sqlcon;
   cmd.ExecuteNonQuery ();
   GridView1.EditIndex = -1;
   showgrid ();
}

load_department() is used to populate Department Dropdownlist:

C#
public DataTable load_department()
   {
   DataTable dt = new DataTable();
   sqlcon = new SqlConnection(con);
   sqlcon.Open();
   string sql = "select * from department";
   SqlCommand cmd = new SqlCommand(sql);
   cmd.CommandType = CommandType.Text;
   cmd.Connection = sqlcon;
   SqlDataAdapter sd = new SqlDataAdapter(cmd);
   sd.Fill(dt);
   return dt;
}

Points to Remember

We need to use the code below in Page_load() method, unless within GridView1_RowUpdating() we can’t catch new edited value.

C#
protected void Page_Load(object sender, EventArgs e)
   {
       if (!IsPostBack)
       {
           showgrid();
       }
   }

History

  • 15th June, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
I am from India, currently i am working in Microsoft Platform for building web and mobile applications.

Comments and Discussions

 
QuestionGetting exception if I add checkbox as EditItemTemplate and checkbox is not recognized Pin
Member 261294812-Dec-19 22:22
Member 261294812-Dec-19 22:22 
QuestionEditable Gridview with Textbox, CheckBox, Radio Button and DropDown List Pin
Member 1237725314-Nov-19 19:46
Member 1237725314-Nov-19 19:46 
Questionsame code for c# Pin
MEGHA KUMAR3-Apr-19 23:31
MEGHA KUMAR3-Apr-19 23:31 
Questionhow add data from this grid Pin
Member 1305587215-Mar-17 22:58
Member 1305587215-Mar-17 22:58 
QuestionEditable Gridview with Textbox, CheckBox, Radio Button and DropDown List sample Pin
incobilgisayar22-Apr-16 22:03
incobilgisayar22-Apr-16 22:03 
QuestionHelped me out a lot! Pin
Member 1091073010-Nov-14 12:22
Member 1091073010-Nov-14 12:22 
QuestionINPUT AND OUPUT PARAMETERS IN STORED PROCEDURE Pin
shashi keshar5-Jul-14 2:33
shashi keshar5-Jul-14 2:33 
QuestionGreat piece of help Pin
Syed Baqer Naqvi22-May-14 5:02
professionalSyed Baqer Naqvi22-May-14 5:02 
GeneralMy vote of 5 Pin
Syed Baqer Naqvi22-May-14 5:01
professionalSyed Baqer Naqvi22-May-14 5:01 
GeneralHow do you handle multiple checkboxes with a varchar field in the database? Pin
dmsWebDev14-Jan-14 11:11
dmsWebDev14-Jan-14 11:11 
QuestionProblem in gridview with edit having dropdown Pin
Member 99590141-Apr-13 22:28
professionalMember 99590141-Apr-13 22:28 
GeneralMy vote of 5 Pin
alonenaveen31-Mar-13 23:01
alonenaveen31-Mar-13 23:01 
QuestionRequest for Add and Delete Pin
Girish_Sharma22-Mar-13 0:56
Girish_Sharma22-Mar-13 0:56 
QuestionNeed help Pin
Meherab Bhamgara9-Mar-13 1:31
Meherab Bhamgara9-Mar-13 1:31 
QuestionNice article Pin
Hameed ul Haq11-Jan-13 21:53
Hameed ul Haq11-Jan-13 21:53 
Nice Article
Questionnice Pin
Pritesh Aryan28-Aug-12 17:52
Pritesh Aryan28-Aug-12 17:52 
GeneralNice work ! Pin
ibrahim.sencan4-Jul-12 1:55
ibrahim.sencan4-Jul-12 1:55 
QuestionUpdating not working Pin
dhage.prashant0128-Jun-11 0:49
dhage.prashant0128-Jun-11 0:49 
GeneralDatabase backup is not a good idea.... Pin
wonder tomato1-Dec-10 23:26
wonder tomato1-Dec-10 23:26 
QuestionVery good job but two questions left Pin
MoeSays1-Dec-10 5:19
MoeSays1-Dec-10 5:19 
GeneralMy vote of 5 Pin
shanawazway23-Nov-10 20:19
shanawazway23-Nov-10 20:19 
GeneralCode Suggestion Pin
Irwan Hassan23-Jun-09 2:38
Irwan Hassan23-Jun-09 2:38 
GeneralGood Job~! Pin
Watson Jason22-Jun-09 21:55
Watson Jason22-Jun-09 21:55 
GeneralMy vote of 2 Pin
Dinesh Mani22-Jun-09 18:00
Dinesh Mani22-Jun-09 18:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.