Home > DeveloperSection > Blogs > Textbox, Dropdown, Checkbox in Editable GridView in Asp.Net

Textbox, Dropdown, Checkbox in Editable GridView in Asp.Net


ASP.Net ASP.Net 
Ratings:
1 Comment(s)
 7520  View(s)
Rate this:

Textbox, Dropdown, Checkbox in Editable GridView in Asp.Net

In this blog, I’m explaining how to add the textbox, dropdown, checkbox in editable gridview in asp.net

Step 1:

Create an asp.net empty web application and add a web form to it.

Step 2:

Add a gridview to the web from by drag and drop from the toolbox and add the columns to the gridview like this:

Add the below code to your .aspx file:

<asp:GridView ID="GridView1" runat="server"

OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowCommand="GridView1_RowCommand"

OnRowDataBound="GridView1_RowDataBound"

OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"

OnRowUpdating="GridView1_RowUpdating"

ShowFooter="true" Width="75%" DataKeyNames="id" BorderColor="#CCCCCC" BorderStyle="Solid"

BorderWidth="1px" AutoGenerateColumns="False" >

<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>

<%--Name--%>

<asp:TemplateField HeaderText="Employee Name" HeaderStyle-Width="10%">

<ItemTemplate>

<asp:Label ID="lblName" runat="server" Text='<%#Eval("name") %>'></asp:Label>

</ItemTemplate>

<EditItemTemplate>

<asp:TextBox ID="txtName" runat="server" Text='<%#Eval("name") %>'></asp:TextBox>

</EditItemTemplate>

<FooterTemplate>

<asp:TextBox ID="txtAddName" runat="server"></asp:TextBox>

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"

 

ValidationGroup="valGrp" ControlToValidate="txtAddName"

ErrorMessage="*"></asp:RequiredFieldValidator>

</FooterTemplate>

</asp:TemplateField>

<%--Department--%>

<asp:TemplateField HeaderText="Department" HeaderStyle-Width="10%">

<ItemTemplate>

<asp:Label ID="lblDepartment" runat="server" Text='<%#Eval("department") %>'></asp:Label>

</ItemTemplate>

<EditItemTemplate>

<asp:DropDownList ID="DropDownListDepartment" runat="server"

Width="150"></asp:DropDownList>

</EditItemTemplate>

<FooterTemplate>

<asp:DropDownList ID="DropDownListAddDepartment" runat="server"

Width="150"></asp:DropDownList>

<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*"

 ControlToValidate="DropDownListAddDepartment"

ValidationGroup="valGrp"></asp:RequiredFieldValidator>

</FooterTemplate>

</asp:TemplateField>

<%--Salary--%>

<asp:TemplateField HeaderText="Salary" HeaderStyle-Width="10%">

<ItemTemplate>

<asp:Label ID="lblSalary" runat="server" Text='<%#Eval("salary") %>'></asp:Label>

</ItemTemplate>

<EditItemTemplate>

<asp:TextBox ID="txtSalary" runat="server" Text='<%#Eval("salary") %>'></asp:TextBox>

</EditItemTemplate>

<FooterTemplate>

<asp:TextBox ID="txtAddSalary" runat="server"></asp:TextBox>

<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="*"

ControlToValidate="txtAddSalary" ValidationGroup="valGrp"></asp:RequiredFieldValidator>

</FooterTemplate>

</asp:TemplateField>

<%--Active--%>

<asp:TemplateField HeaderText="Active" HeaderStyle-Width="10%">

<ItemTemplate>

<asp:Label ID="lblActive" runat="server" Text='<%#Eval("active") %>'></asp:Label>

</ItemTemplate>

<EditItemTemplate>

<asp:CheckBox ID="CheckBoxActive" Text="Active" runat="server" />

</EditItemTemplate>

<FooterTemplate>

<asp:CheckBox ID="CheckBoxAddActive" Text="Active" runat="server" />

</FooterTemplate>

</asp:TemplateField>

<%--Link--%>

<asp:TemplateField>

<ItemTemplate>

<asp:LinkButton ID="btnEdit" Text="Edit" CommandName="Edit" runat="server"/>

<asp:LinkButton ID="btnDelete" Text="Delete" CommandName="Delete" runat="server"/>

</ItemTemplate>

<EditItemTemplate>

<asp:LinkButton ID="btnUpdate" Text="Update" CommandName="Update" runat="server"/>

<asp:LinkButton ID="btnCancel" Text="Cancel" CommandName="Cancel" runat="server"/>

</EditItemTemplate>

<FooterTemplate>

<asp:Button ID="btnInset" Text="Insert" CommandName="Insert" runat="server"

ValidationGroup="valGrp"/>

</FooterTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

Your gridview will look like this.


And also add the below events to the gridview:


Step 3:

Now add codes to the events which you have created:

protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                LoadData();

            }

        }

public void LoadData()

        {

            string query = "select * from EmployeeTable;";

            SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["Connect"].ToString());

            conn.Open();

            SqlCommand cmd = new SqlCommand();

            cmd.Connection = conn;

            cmd.CommandText = query;

            cmd.ExecuteNonQuery();

            SqlDataAdapter adap = new SqlDataAdapter(cmd);

            DataTable dt = new DataTable();

            adap.Fill(dt);

            GridView1.DataSource = dt;

            GridView1.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;

        }

RowUpdating

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

        {

            bool blActive = false;

            int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);

            TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");

            DropDownList department = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropDownListDepartment");

            TextBox salary = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtSalary");

            CheckBox active = (CheckBox)GridView1.Rows[e.RowIndex].FindControl("CheckBoxActive");

            if (active.Checked)

                blActive = true;

            else

                blActive = false;

            using (SqlConnection Sqlcon = new SqlConnection(WebConfigurationManager.ConnectionStrings["Connect"].ToString()))

            {

                using (SqlCommand cmd = new SqlCommand())

                {

                    Sqlcon.Open();

                    cmd.Connection = Sqlcon;

                    cmd.CommandType = CommandType.Text;

                    cmd.CommandText = "update EmployeeTable set name ='" + name.Text + "',department= '" + department.SelectedValue + "', salary = '" + salary.Text + "', active='" + blActive + "' where id='" + id + "' ";

                    cmd.ExecuteNonQuery();

                }

            }

            GridView1.EditIndex = -1;

            LoadData();

            lblMessage.Text = "Record updated successfully!";

        }

RowEditing

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

        {

            GridView1.EditIndex = e.NewEditIndex;

            LoadData();

        }

RowDeleting

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

        {

            int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);

 

            using (SqlConnection Sqlcon = new SqlConnection(WebConfigurationManager.ConnectionStrings["Connect"].ToString()))

            {

                using (SqlCommand cmd = new SqlCommand())

                {

                    Sqlcon.Open();

                    cmd.Connection = Sqlcon;

                    cmd.CommandType = CommandType.Text;

                    cmd.CommandText = "delete from EmployeeTable where id ="+id+"";

                    cmd.ExecuteNonQuery();

                }

            }

            GridView1.EditIndex = -1;

            LoadData();

            lblMessage.Text = "Record Deleted";

        }

RowCancelingEdit

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e

        {

            GridView1.EditIndex = -1;

            LoadData();

        }

RowCommand

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

        {

            bool blActive = false;

            if (e.CommandName.Equals("Insert"))

            {

                TextBox name = (TextBox)GridView1.FooterRow.FindControl("txtAddName");

 

                DropDownList department = (DropDownList)GridView1.FooterRow.FindControl("DropDownListAddDepartment");

                TextBox salary = (TextBox)GridView1.FooterRow.FindControl("txtAddSalary");

                CheckBox active = (CheckBox)GridView1.FooterRow.FindControl("CheckBoxAddActive");

                if (active.Checked)

                    blActive = true;

                else

                    blActive = false;

 

                using (SqlConnection Sqlcon = new SqlConnection(WebConfigurationManager.ConnectionStrings["Connect"].ToString()))

                {

                    using (SqlCommand cmd = new SqlCommand())

                    {

                        Sqlcon.Open();

                        cmd.Connection = Sqlcon;

                        cmd.CommandType = CommandType.Text;

                        cmd.CommandText = "insert into EmployeeTable (name, department, salary, active)values('" + name.Text.Trim() + "','" + department.SelectedValue.ToUpper() + "','" + salary.Text.Trim() + "','" + blActive + "') ";

                        cmd.ExecuteNonQuery();

                    }

                }

                GridView1.EditIndex = -1;

                LoadData();

                lblMessage.Text = "Record inserted successfully!";

            }

        }

RowDataBound

protected void GridView1_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("DropDownListDepartment");

                    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("CheckBoxActive");

                    if (drview[4].ToString() == "True")

                    { chkb.Checked = true; }

                    else { chkb.Checked = false; }

                }

            }

            if (e.Row.RowType == DataControlRowType.Footer)

            {

                DropDownList dp = (DropDownList)e.Row.FindControl("DropDownListAddDepartment");

                dp.DataSource = GetEmpDept();

                dp.DataTextField = "DepName";

                dp.DataValueField = "DepName";

                dp.DataBind();

            }

        }

Output

When you run the project, you will get all the record from database.

When you click the update button, you will see the Employee Name change to textbox, Department Change to dropdown, Salary change to textbox and active change to checkbox.

 

Now you can update the record according to your need or you can cancel it.

 

I have updated the department and salary of “Mark David” record , once you have updated the record you will get a message.

Click on delete button to delete a particular record.

I have deleted the “Mark David” record and you will get a message like this:


If you want to insert a new record you can insert like this:

 

The new record “Mark David” will insert when you click on insert button and you will get a message.




Edit delete and update gridview

By Jafar Shah on   6 months ago
Excellent demo with step by step guidance. I really appreciate your efforts. 

Don't want to miss updates? Please click the below button!

Follow MindStick