Inserting a Row Within a Gridview footer

1

Written on 3:30 PM by Mj blog

Let's see how to insert a row in gridview from its footer template, Normally we will have seperate div area where we keep our Label and texbox and dropdownlist seperately and we will have a add button lets now reduce the space constraint by providing those controls on the footer template of the gridview and save space, we also know that by default gridview does not supports inserting data but now we are going to override that rule

Issues and work around
Before doing this there is special case when the database has no records the gridview never appears rite what shall we do this problem for this i have given a solution in my last blog check it . I am adding that source code also with this blog

Our Scenario
In this scenario I am going to have three columns one is ID column which will not be inserted and secound is Name which needs to be inserted hence we place a textbox and there is Status selection hence we are keeping a dropdownlist in the footer control then create a template for insert button

Now the steps to be followed


Step 1: Place a gridview and bind it with the database, create columns in the gridview and convert that to template

Step 2: Place Footer template for each column that to be inserted and create the controls we need for inserting the row

step 3 : Here we are going to bind our dropdownlist , to do so create gridview rowcreated event and bind the dropdownlist

Step 4: Then create a onclick event for insert button , provide the CommandName="Insert" and write the code for inserting the records in database

Let's see the HTML Source code


<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="False" DataKeyNames
="Id" CellPadding="4" ForeColor="Black" GridLines="Vertical" ShowFooter="True" BackColor="White"
BorderColor="#DEDFDE" BorderStyle="Solid"
BorderWidth="2px" OnRowCreated
="GridView1_RowCreated">
<RowStyle BackColor="#F7F7DE" />
<Columns>
<asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="ID">
<EditItemTemplate>

<asp:Label ID="Label1" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<EditItemTemplate>

<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="isactive">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("isactive") %>'></asp:TextBox>

</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("isactive") %>'></asp:Label> </ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlIsActive" runat="server">
</asp:DropDownList>
</FooterTemplate> </asp:TemplateField>
<asp:TemplateField FooterStyle-HorizontalAlign="Center">
<FooterTemplate>
<asp:Button ID="btnInsert" runat="server" Text="Insert" CommandName="Insert" OnClick="InsertRows" />
</FooterTemplate>
</asp:TemplateField>
</Columns>

<FooterStyle BackColor="#CCCC99" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<EmptyDataTemplate>
No Record Found
</EmptyDataTemplate>
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />

</asp:GridView>

Lets See the C# Code


using System;

using System.Collections.Generic;

using System.Collections;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Xml;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;


public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
BindGrid(); //Binding the gridview on page load
}
}
/// <summary>
/// This method connect to Sql database, fetch data returns dataset
/// </summary>
/// <returns></returns>
public DataSet ReturnMenuDetails()
{
DataSet ds = new DataSet();
using (SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings ["SqlConnectionString"].ConnectionString.ToString()))
{
sqlconn.Open();
SqlDataAdapter sqldap = new
SqlDataAdapter("select ID , Name , isactive from detail", sqlconn);
sqldap.Fill(ds);
}
return ds;
}
/// <summary>
/// This method return a datatable with empty row
/// </summary>
/// <returns></returns>
public DataTable ReturnEmptyDataTable()
{
DataTable dtMenu = new DataTable(); //declaringa datatable
DataColumn dcMenuID = new DataColumn("ID", typeof(System.Int32));

//creating a column in the same
//Name of column available in the sql server
dtMenu.Columns.Add(dcMenuID);// Adding column to the datatable

DataColumn dcMenuName = new
DataColumn("Name", typeof(System.String));
dtMenu.Columns.Add(dcMenuName);

DataColumn dcMenuActive = new
DataColumn("isactive", typeof(System.String));
dtMenu.Columns.Add(dcMenuActive);
DataRow datatRow = dtMenu.NewRow();

//Inserting a new row,datatable .newrow creates a blank row
dtMenu.Rows.Add(datatRow);//adding row to the datatable
return dtMenu;
}
/// <summary>
/// This method checks for no of rows returned from sql server and binds the
/// datasource with the gridview based on the resultset, if no rows returned are zero
/// from sql server then it will bind the datatable to the gridview to display the columns
/// when no record was returned
/// </summary>
public void BindGrid()
{
if (ReturnMenuDetails().Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ReturnMenuDetails();
}
else {
GridView1.DataSource = ReturnEmptyDataTable();

}
GridView1.DataBind();
}
/// <summary>
/// This method will search the dropdownlist in the footer template of the gridview
/// and bind the dropdownlist for this example i have used arraylist
/// we can bind from database also
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
//Checking whether the rended row is footer
if (e.Row.RowType == DataControlRowType.Footer)
{
ArrayList arraDropdown = new ArrayList();
arraDropdown.Add(new ListItem("Select", "-1"));
arraDropdown.Add(new ListItem("Yes", "Yes"));
arraDropdown.Add(new ListItem("No", "No"));
//searching for dropdownlist in the footer view of gridview
DropDownList ddl = (DropDownList)e.Row.Cells[0].FindControl("ddlIsActive");
//Binding the dropdownlist with arraylist
ddl.DataSource = arraDropdown;
ddl.DataBind();
}
}
/// <summary>
/// This method will be fired when ever the insert button is clicked
/// This method searches for the textbox and dropdownlist placed in
/// the footer template of gridview and passes the values to the
/// SQL query and binds the grid
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void InsertRows(object sender, EventArgs e)
{
TextBox txtName = (TextBox)GridView1.FooterRow.FindControl("TextBox4");
DropDownList ddlys = (DropDownList)GridView1.FooterRow.FindControl("ddlIsActive");
using (SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings ["SqlConnectionString"].ConnectionString.ToString()))
{
SqlCommand sqldap = new
SqlCommand("insert into switch_master(switch_Name,isactive,created_by) values ('" + txtName.Text + "','" + ddlys.SelectedItem.Text + "','Manoj')", sqlconn);
sqlconn.Open();
sqldap.ExecuteNonQuery();
}
BindGrid();
}
}


Thus we can insert new rows in the within gridview

If you enjoyed this post Subscribe to our feed

1 Comment

  1. Anonymous |

    Hi! Its working fine.

     

Post a Comment