Home > Articles > ASP.NET Articles > Dropdown, checkbox and textbox controls in asp.net editable Gridview.

Dropdown, checkbox and textbox controls in asp.net editable Gridview.

by Thamil   on Jul 08, 2013   Category: ASP.NET  | Level: Intermediate  |  Views: 31880    |  Points: 100   
Like this article? Bookmark and Share:
In this article, I will explain how to use dropdown, checkbox and textbox controls in gridview while insert and edit records.


Introduction


Gridview is most powerful and useful control in asp.net applications and have lot of built in features such as sorting, paging, editing, delete, and formatting etc. in this article we will see, some frequently asked questions about working with dropdown, checkbox and textbox controls in gridview. In my previous article I have explained in detail about How to perform insert, update, delete and select rows in ASP.NET gridview control using stored procedure , so in this article I will explain in briefly how to add these mentioned controls for these CRUD operations.

 

Step1: Create asp.net project


I'm using visual studio 2008 and sql server 2008 for this sample project. Create an asp.net project and drag the gridview control then configure the database connection string in web.config file as shown below.

<connectionStrings>
  <add name="ConnectionString" connectionString="Data Source=TEST-PC\SQLEXPRESS;Initial Catalog=TEST_DB;Integrated Security=True" providerName="System.Data.SqlClient"/>
 </connectionStrings>

 

Step2: Design Gridview page:

 

Copy and past the below code in your project.

<div style="font-size: 20px; font-family: Verdana">
        <u>Sample - Gridview with dropdown and checkbox Controls</u>
        <br />
        <br />
    </div>
    <div>
        <asp:GridView ID="GridViewSample" runat="server" AutoGenerateColumns="False" Font-Names="Verdana"
            AllowPaging="true" ShowFooter="true" PageSize="5" Width="75%" DataKeyNames="Emp_id" OnPageIndexChanging="GridViewSample_PageIndexChanging"
            OnRowCancelingEdit="GridViewSample_RowCancelingEdit" OnRowEditing="GridViewSample_RowEditing"
            OnRowUpdating="GridViewSample_RowUpdating" OnRowCommand="GridViewSample_RowCommand"
            BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" OnRowDataBound="GridViewSample_RowDataBound">
            <AlternatingRowStyle BackColor="#FFD4BA" />
            <FooterStyle BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
            <PagerStyle BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
            <HeaderStyle Height="30px" BackColor="#BC3670" Font-Size="15px" BorderColor="#CCCCCC"
                BorderStyle="Solid" BorderWidth="1px" />
            <RowStyle Height="20px" Font-Size="13px" BorderColor="#CCCCCC" BorderStyle="Solid"
                BorderWidth="1px" />
            <Columns>
                <asp:TemplateField HeaderText="Employee Name" HeaderStyle-Width="10%">
                    <ItemTemplate>
                        <asp:Label ID="lblEmpName" runat="server" Text='<%#Eval("Emp_Name") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtEmpName" runat="server" Text='<%#Eval("Emp_Name") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtAddEmpName" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="reqName" ValidationGroup="ValgrpCust" ControlToValidate="txtAddEmpName"
                            runat="server" ErrorMessage="*"></asp:RequiredFieldValidator>
                    </FooterTemplate>
                    <HeaderStyle Width="15%"></HeaderStyle>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Job" HeaderStyle-Width="15%">
                    <ItemTemplate>
                        <asp:Label ID="lblJob" runat="server" Text='<%#Eval("Emp_job") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtEmpJob" runat="server" Text='<%#Eval("Emp_job") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtAddEmpJob" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="reqAdd1" ValidationGroup="ValgrpCust" ControlToValidate="txtAddEmpJob"
                            runat="server" ErrorMessage="*"></asp:RequiredFieldValidator>
                    </FooterTemplate>
                    <HeaderStyle Width="15%"></HeaderStyle>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Department" HeaderStyle-Width="15%">
                    <ItemTemplate>
                        <asp:Label ID="lblEmpDep" runat="server" Text='<%#Eval("Emp_Dep") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList ID="DrpDwnEmpDept" runat="server" Width="150px">
                        </asp:DropDownList>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList ID="DrpDwnAddEmpDept" runat="server" Width="150px">
                        </asp:DropDownList>
                        <asp:RequiredFieldValidator ID="reqAdd2" ValidationGroup="ValgrpCust" ControlToValidate="DrpDwnAddEmpDept"
                            runat="server" ErrorMessage="*"></asp:RequiredFieldValidator>
                    </FooterTemplate>
                    <HeaderStyle Width="15%"></HeaderStyle>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Active" HeaderStyle-Width="10%">
                    <ItemTemplate>
                        <asp:Label ID="lblActive" runat="server" Text='<%#Eval("Active") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:CheckBox ID="ChckBxActive" Text="Active" runat="server"></asp:CheckBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:CheckBox ID="ChckBxAddActive" Text="Active" runat="server"></asp:CheckBox>
                    </FooterTemplate>
                    <HeaderStyle Width="10%"></HeaderStyle>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Edit" HeaderStyle-Width="15%">
                    <ItemTemplate>
                        <asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
                        <asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:Button ID="btnInsertRecord" runat="server" Text="Add" ValidationGroup="ValgrpCust"
                            CommandName="Insert" />
                    </FooterTemplate>
                    <HeaderStyle Width="15%"></HeaderStyle>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    <div>
        <br />
        <asp:Label ID="lblMessage" ForeColor="Green" Font-Bold="true" runat="server" Text=""></asp:Label>
    </div>

In the above code, we have added the textbox, dropdown and checkbox in EditItemtemplate and FooterTemplate inside TemplateField to edit and add the values. This EditItemtemplate used to display the data in edit mode under Templatefield, so we will add the dropdown, textbox and checkbox controls to display the data while update, same while inserting the data we use FooterTemplate to display the footer section in gridview to insert the records and add these dropdown, textbox and checkbox controls in this template

Step3: Code behind part

In page load event, display the data in gridview using LoadData() function, here we are executing select text command and getting the data.

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }
        private void LoadData()
        {
            using (SqlConnection Sqlcon = new SqlConnection(strCon))
            {
                string strSelQuery = "SELECT [Emp_id],[Emp_Name],[Emp_job],[Emp_Dep],[Active] FROM dbo.tblEmployee;";
                using (SqlCommand cmd = new SqlCommand())
                {
                    Sqlcon.Open();
                    cmd.Connection = Sqlcon;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = strSelQuery;
                    SqlAda = new SqlDataAdapter(cmd);
                    ds = new DataSet();
                    SqlAda.Fill(ds);
                    GridViewSample.DataSource = ds;
                    GridViewSample.DataBind();
                }
            }
        }

Using this RowDataBound event, load the epmloyee departments in dropdown list values while editing the record and load these values again when a datarow is bound to data in gridview control footer section. Also assign checkbox values while editing the datarow.

 protected void GridViewSample_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            DataRowView drview = e.Row.DataItem as DataRowView;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    DropDownList dpEmpdept = (DropDownList)e.Row.FindControl("DrpDwnEmpDept");
                    DataTable dt = GetEmpDept();
                    dpEmpdept.DataSource = GetEmpDept();
                    dpEmpdept.DataTextField = "DepName";
                    dpEmpdept.DataValueField = "DepName";
                    dpEmpdept.DataBind();
                    dpEmpdept.SelectedValue = drview[2].ToString();
                    CheckBox chkb = (CheckBox)e.Row.FindControl("ChckBxActive");
                    if (drview[4].ToString() == "True")
                    {chkb.Checked = true;}
                    else{ chkb.Checked = false;}
                }
            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                DropDownList dp = (DropDownList)e.Row.FindControl("DrpDwnAddEmpDept");
                dp.DataSource = GetEmpDept();
                dp.DataTextField = "DepName";
                dp.DataValueField = "DepName";
                dp.DataBind();
            }
        }
        private DataTable GetEmpDept()
        {
            //Get Employee department
            DataTable dt = new DataTable();
            dt.Columns.Add("DepName");
            DataRow rw1 = dt.NewRow();
            rw1[0] = "IT";
            dt.Rows.Add(rw1);
            DataRow rw2 = dt.NewRow();
            rw2[0] = "Finance";
            dt.Rows.Add(rw2);
            DataRow rw3 = dt.NewRow();
            rw3[0] = "Security";
            dt.Rows.Add(rw3);
            return dt;
        }

The RowCommand event occure when button is clicked in a gridview control and use this event to add the records into database.

protected void GridViewSample_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            bool blActive = false;
            if (e.CommandName.Equals("Insert"))
            {
                TextBox EmpName = (TextBox)GridViewSample.FooterRow.FindControl("txtAddEmpName");
                TextBox job = (TextBox)GridViewSample.FooterRow.FindControl("txtAddEmpJob");
                DropDownList Dep = (DropDownList)GridViewSample.FooterRow.FindControl("DrpDwnAddEmpDept");
                CheckBox Active = (CheckBox)GridViewSample.FooterRow.FindControl("ChckBxAddActive");
                if (Active.Checked) blActive = true; else blActive = false;
                using (SqlConnection Sqlcon = new SqlConnection(strCon))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        Sqlcon.Open();
                        cmd.Connection = Sqlcon;
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = "insert into [dbo].[tblEmployee] (Emp_Name,Emp_job ,Emp_Dep ,Active ,Created_by,Created_On)values('" + EmpName.Text.Trim() + "','" + job.Text.Trim() + "','" + Dep.SelectedValue.ToUpper() + "','" + blActive + "','Admin','"+DateTime.Now+"') ";
                        cmd.ExecuteNonQuery();
                    }
                }
                GridViewSample.EditIndex = -1;
                LoadData();
                lblMessage.Text = "Record inserted successfully!";
            }
        }
The RowUpdating event will occur when rows update button is clicked, using this event update the record as like below.
protected void GridViewSample_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            bool blActive       = false;
            int EmployeeID = Convert.ToInt32(GridViewSample.DataKeys[e.RowIndex].Value);
            TextBox EmpName = (TextBox)GridViewSample.Rows[e.RowIndex].FindControl("txtEmpName");
            TextBox job = (TextBox)GridViewSample.Rows[e.RowIndex].FindControl("txtEmpJob");
            DropDownList Dep = (DropDownList)GridViewSample.Rows[e.RowIndex].FindControl("DrpDwnEmpDept");
            CheckBox Active = (CheckBox)GridViewSample.Rows[e.RowIndex].FindControl("ChckBxActive");
            if (Active.Checked) blActive = true; else blActive = false;
            using (SqlConnection Sqlcon = new SqlConnection(strCon))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    Sqlcon.Open();
                    cmd.Connection = Sqlcon;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "update dbo.tblEmployee set Emp_Name ='" + EmpName.Text + "' ,Emp_job = '" + job.Text + "',Emp_Dep= '" + Dep.SelectedValue + "', Active='" + blActive + "' where Emp_id='" + EmployeeID + "' ";
                    cmd.ExecuteNonQuery();
                }
            }
            GridViewSample.EditIndex = -1;
            LoadData();
            lblMessage.Text = "Record updated successfully!";
        }

I have attached the sample project and sql scripts in this article. Open the project and change the connection string in web.config file and execute sql scripts in your test database and run the project. I hope this article will help you how to add dropdown, textbox and checkbox controls and load data while edit and insert the data in gridview control. Please provide your suggestions and feedback.





Like this article? Bookmark and Share:

Most viewed Articles

User Comments


  Re :Dropdown, checkbox and textbox controls in asp.net editable Gridview.   
Posted by Mathiyarasan
on 11/27/2013 1:28:48 AM
Points : 10

Nice.. good effort..

Submit feedback about this article

Please sign in to post feedback

Latest Posts