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:GridViewID="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">
<AlternatingRowStyleBackColor="#FFD4BA"/>
<FooterStyleBorderColor="#CCCCCC"BorderStyle="Solid"BorderWidth="1px"/>
<PagerStyleBorderColor="#CCCCCC"BorderStyle="Solid"BorderWidth="1px"/>
<HeaderStyleHeight="30px"BackColor="#BC3670"Font-Size="15px"BorderColor="#CCCCCC"
BorderStyle="Solid"BorderWidth="1px"/>
<RowStyleHeight="20px"Font-Size="13px"BorderColor="#CCCCCC"BorderStyle="Solid"
BorderWidth="1px"/>
<Columns>
<%--Name--%>
<asp:TemplateFieldHeaderText="Employee Name"HeaderStyle-Width="10%">
<ItemTemplate>
<asp:LabelID="lblName"runat="server"Text='<%#Eval("name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBoxID="txtName"runat="server"Text='<%#Eval("name") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBoxID="txtAddName"runat="server"></asp:TextBox>
<asp:RequiredFieldValidatorID="RequiredFieldValidator1"runat="server"
ValidationGroup="valGrp"ControlToValidate="txtAddName"
ErrorMessage="*"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<%--Department--%>
<asp:TemplateFieldHeaderText="Department"HeaderStyle-Width="10%">
<ItemTemplate>
<asp:LabelID="lblDepartment"runat="server"Text='<%#Eval("department") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownListID="DropDownListDepartment"runat="server"
Width="150"></asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownListID="DropDownListAddDepartment"runat="server"
Width="150"></asp:DropDownList>
<asp:RequiredFieldValidatorID="RequiredFieldValidator2"runat="server"ErrorMessage="*"
ControlToValidate="DropDownListAddDepartment"
ValidationGroup="valGrp"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<%--Salary--%>
<asp:TemplateFieldHeaderText="Salary"HeaderStyle-Width="10%">
<ItemTemplate>
<asp:LabelID="lblSalary"runat="server"Text='<%#Eval("salary") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBoxID="txtSalary"runat="server"Text='<%#Eval("salary") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBoxID="txtAddSalary"runat="server"></asp:TextBox>
<asp:RequiredFieldValidatorID="RequiredFieldValidator3"runat="server"ErrorMessage="*"
ControlToValidate="txtAddSalary"ValidationGroup="valGrp"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<%--Active--%>
<asp:TemplateFieldHeaderText="Active"HeaderStyle-Width="10%">
<ItemTemplate>
<asp:LabelID="lblActive"runat="server"Text='<%#Eval("active") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBoxID="CheckBoxActive"Text="Active"runat="server"/>
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBoxID="CheckBoxAddActive"Text="Active"runat="server"/>
</FooterTemplate>
</asp:TemplateField>
<%--Link--%>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButtonID="btnEdit"Text="Edit"CommandName="Edit"runat="server"/>
<asp:LinkButtonID="btnDelete"Text="Delete"CommandName="Delete"runat="server"/>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButtonID="btnUpdate"Text="Update"CommandName="Update"runat="server"/>
<asp:LinkButtonID="btnCancel"Text="Cancel"CommandName="Cancel"runat="server"/>
</EditItemTemplate>
<FooterTemplate>
<asp:ButtonID="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:
protectedvoid Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
}
}
publicvoid LoadData()
{
string query = "select * from EmployeeTable;";
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["Connect"].ToString());
conn.Open();
SqlCommand cmd = newSqlCommand();
cmd.Connection = conn;
cmd.CommandText = query;
cmd.ExecuteNonQuery();
SqlDataAdapter adap = newSqlDataAdapter(cmd);
DataTable dt = newDataTable();
adap.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
privateDataTable GetEmpDept()
{
//Get Employee department
DataTable dt = newDataTable();
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
protectedvoid 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 = newSqlConnection(WebConfigurationManager.ConnectionStrings["Connect"].ToString()))
{
using (SqlCommand cmd = newSqlCommand())
{
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
protectedvoid GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
LoadData();
}
RowDeleting
protectedvoid GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
using (SqlConnection Sqlcon = newSqlConnection(WebConfigurationManager.ConnectionStrings["Connect"].ToString()))
{
using (SqlCommand cmd = newSqlCommand())
{
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
protectedvoid GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e
{
GridView1.EditIndex = -1;
LoadData();
}
RowCommand
protectedvoid 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 = newSqlConnection(WebConfigurationManager.ConnectionStrings["Connect"].ToString()))
{
using (SqlCommand cmd = newSqlCommand())
{
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
protectedvoid GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView drview = e.Row.DataItem asDataRowView;
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.
Jafar Shah
19-May-2016