Nested GridView in ASP.net


In this Artical i'm trying to explain about nested gridview.. Here in Parent Grid columns are Name, Number Child Grid Columns are Qty , Mat.. We try to add multiple mat for a specified number in parent Grid.. for this purpose we introduce Nested Grid Concept on here...

In this artical i'm trying to explain how to handle inner grid and how to enter rows from footer of inner grid to eliminate duplicate records..

1) declare a parent grid in that columns are id,no,name

2) declare child grid in any one template and add 3 controls in footer template a) mat selection b) qty enter c) add button

3) if we choose mat value 7 no need to enter qty columns , for this reason bydeafult define that textbox and Add button enabled "false".

4) to handle numbers while enter the qty in textbox in proper manner, if we eneter in inappropriate manner then also we arrange that in proper way using the javascript code.

5) if record already enter again we try to enter the details then no need to enter again first we delete previous record what are exists in earlier and then enter again..


JavaScript Code :



This code helps for in each mat we are enter some qty..
If the Qty we are enter in wrong format

1) to handle number format
2) to handle Signs + , -.



<script type="text/javascript">
function IsNumFieldKeyPress() {
var element;
element = event.srcElement;
if (event.keyCode >= 48 && event.keyCode <= 57) {//to handle num 0 -9
event.returnValue = true;
return;
}
else if (event.keyCode == 46) { // to handle "."
if (element.value.indexOf('.', 0) == -1) {
event.returnValue = true;
return;
}
}
else if (event.keyCode == 43) { // to handle +
if (element.value == undefined)
element.value = "+";
else if (element.value.charAt(0) != "+" && element.value.charAt(0) != "-")
element.value = "+" + element.value;
}
else if (event.keyCode == 45) { // to handle -
if (element.value == undefined)
element.value = "-";
else if (element.value.charAt(0) != "-" && element.value.charAt(0) != "+")
element.value = "-" + element.value;
}
event.returnValue = false;
}
</script>



Source Code :




<asp:DataGrid ID="gd" runat="server" AutoGenerateColumns="False"
BorderColor="Black" BorderStyle="Solid" Width="100%" BorderWidth="1px"
CellPadding="1" CssClass="ArialNarrow" GridLines="Vertical"
DataKeyField="Id" OnItemDataBound="gd_ItemDataBound" >

<Columns>
<asp:TemplateColumn HeaderText="Name" HeaderStyle-Width="20%">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateColumn>

<asp:TemplateColumn HeaderText="No">
<ItemTemplate>
<asp:Label ID="lblNo" runat="server" Text='<%# Eval("No")%>' />
<asp:Label ID="lblId" runat="server" Text='<%# Eval("Id") %>' Visible="false" />
</ItemTemplate>
</asp:TemplateColumn>

<asp:TemplateColumn >
<ItemTemplate>
<div id="div1" runat="server">
<asp:GridView ID="GV" runat="server" GridLines=None
Width="200px" AutoGenerateColumns="false" ShowFooter="True"
ShowHeader="False" OnRowCommand="GV_RowCommand"
OnRowDataBound="GV_RowDataBound" OnRowDeleting="GV_RowDelete"
DataKeyNames="DED_Id">

<Columns>

<asp:TemplateField>
<FooterTemplate>
<asp:DropDownList ID="ddlMat"
runat="server" Width="100%" AutoPostBack="true"
OnSelectedIndexChanged="ddlMat_SelectedIndexChanged" />
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblId" runat="server"
visible="false"/>
<asp:Label ID="lblMat" runat="server" Text='<%# Eval("DED_Name") %>' />
<asp:Label ID="LblMatValue" runat="server" Text='<%# Eval("DED_Id") %>'
Visible="false" />
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField >
<FooterTemplate>
<asp:TextBox ID="txtMatQty" runat="server" width="90%" onkeypress="IsNumFieldKeyPress();" Enabled="false"/>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblMatQty" runat="server" Text='<%# Eval("Qty") %>' />
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField >
<ItemTemplate>
<asp:LinkButton ID="btnDelete" Text="Delete" CommandName="Delete" runat="server" Visible="True" CommandArgument= '<%# Eval("DED_Id") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkAdd" Text="Add" CommandName="Add" Enabled="false" runat="server" />
</FooterTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>
</div>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>





Code Behind :





using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Telerik.WebControls;

public partial class NestedGridView : System.Web.UI.Page
{
string Code, Web_Login;
private const string ITEMS = "CheckedItems";
DataTable gbds, dt;
DataSet dsDocument;



protected void Page_Load(object sender, EventArgs e)
{
lntSPCurrentSite objCurrentSite = new lntSPCurrentSite();
lntSPCurrentUser objCurrentUser = new lntSPCurrentUser();
Design objDesign = new Design();

Code = objCurrentSite.WebSiteName;
Web_Login = objCurrentUser.LoginName;

if (!IsPostBack)
{
Columns();
Session[ITEMS] = null;
DocumentNo();
}
}

//Display for Empty GridView (child)
public void Columns()
{
DataTable dt = new DataTable();
dt.Columns.Add("DED_Id", typeof(int));
dt.Columns.Add("DED_Name", typeof(string));
dt.Columns.Add("Qty", typeof(string));
dt.Columns.Add("Id", typeof(int));
ViewState["dt"] = dt;
ViewState["col"] = dt;
ViewState["dtBind"] = dt;
}

//bind parent grid
protected void DocumentNo()
{
Design objDesign = new Design();
dsDocument = //Bind data
dt = dsDocument.Tables[0];
Session["datatable"] = dt;
ViewState["datatable"] = dt;
gd.DataSource = dsDocument;
gd.DataBind();
}

protected void gd_ItemDataBound(object sender, DataGridItemEventArgs e)
{

if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Design objDesign = new Design();
DataGridItem item = (DataGridItem)e.Item;
int Id = Convert.ToInt32(gd.DataKeys[item.ItemIndex]);


//find the inner grid control
GridView GV = (GridView)e.Item.FindControl("GV");

DataSet ds = //bind material details

DataTable dt;
dt = ViewState["dt"] as DataTable;
DataTable dt1 = dt.Clone();

foreach (DataRow d in dt.Select("Id=" + Id))
{
DataRow drow = dt1.NewRow();
drow["DED_Id"] = d["DED_Id"];
drow["DED_Name"] = d["DED_Name"];
drow["Qty"] = d["Qty"];
drow["Id"] = d["Id"];
dt1.Rows.Add(drow);
}

if (dt1.Rows.Count == 0 || dt.Rows.Count == 0)
{
DataRow dr = dt.NewRow();
DataRow dr1 = dt1.NewRow();
dt.Rows.Add(dr);
dt1.Rows.Add(dr1);
}
ViewState["ds"] = ds;

//Bind data to inner grid
GV.DataSource = dt1;
GV.DataBind();

if (((Label)GV.Rows[0].FindControl("lblMat")).Text == "")
{
GV.Rows[0].Visible = false;
if (dt.Rows.Count > 1)
{
int count = dt.Rows.Count;
dt.Rows.RemoveAt(count - 1);
}
else
{
dt.Rows.RemoveAt(0);
dt1.Rows.RemoveAt(0);
}
}
}
}

protected void GV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DataSet ds = new DataSet();
ds = ViewState["ds"] as DataSet;
DropDownList ddlMat = (DropDownList)e.Row.FindControl("ddlMat");

ddlMat.DataSource = ds;
ddlMat.DataTextField = "DED_Name";
ddlMat.DataValueField = "DED_Id";
ddlMat.DataBind();
ddlMat.SelectedIndex = 6;
}
}

protected void ddlMat_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
int value = Convert.ToInt32(ddl.SelectedValue);
ViewState["DDL"] = value;
GridViewRow gvr = (GridViewRow)ddl.Parent.Parent;
TextBox txt = (TextBox)gvr.FindControl("txtMatQty");
LinkButton lnkbtn = (LinkButton)gvr.FindControl("lnkAdd");


if (value == 7 || value == 0)
{
txt.Text = "";
txt.Enabled = false;
lnkbtn.Enabled = false;
}
else
{
txt.Enabled = true;
lnkbtn.Enabled = true;
}
}
protected void GV_RowDelete(object sender, GridViewDeleteEventArgs e)
{

}
protected void GV_RowCommand(object sender, GridViewCommandEventArgs e)
{
DataTable dt1 = ViewState["dt"] as DataTable;
GridView grid = (GridView)sender;

DataGridItem item = grid.NamingContainer as DataGridItem;
//find the DataKey name
int Id = Convert.ToInt32(gd.DataKeys[item.ItemIndex]);

if (e.CommandName == "Add")
{
//find the footer row controls
DropDownList ddlMat = (DropDownList)grid.FooterRow.FindControl("ddlMat");
TextBox txtMatQty = (TextBox)grid.FooterRow.FindControl("txtMatQty");

string Mat = (grid.FooterRow.FindControl("ddlMat") as DropDownList).SelectedItem.Text;
ViewState["mat"] = Mat;
int Mat_Id = Convert.ToInt32((grid.FooterRow.FindControl("ddlMat") as DropDownList).SelectedValue);
string Qty = (grid.FooterRow.FindControl("txtMatQty") as TextBox).Text;


DataRow dr;
dr = dt1.NewRow();
DataTable dtBind = dt1.Clone();


if (Mat_Id != 7)
{
dr["DED_Id"] = Mat_Id;
dr["DED_Name"] = Mat;
//user not enter quantity columns, budefault we consider as"0"
if (Qty == "")
{
dr["Qty"] = "0";
}
else
{
dr["Qty"] = Qty;
}
dr["Id"] = Id;


if (dt1.Rows.Count == 0)
{
dt1.Rows.Add(dr);
dt1.AcceptChanges();
}
else
{
//to overcome the duplication

DataRow[] drs = dt1.Select("DED_Id=" + Mat_Id + " AND Id=" + Id);
if (drs != null && drs.Length == 0)
{
dt1.Rows.Add(dr);
dt1.AcceptChanges();
}
}
ViewState["dt"] = dt1;

foreach (DataRow d in dt1.Select("Id=" + Id))
{
DataRow drow = dtBind.NewRow();
drow["DED_Id"] = d["DED_Id"];
drow["DED_Name"] = d["DED_Name"];
drow["Qty"] = d["Qty"];
drow["Id"] = d["Id"];
dtBind.Rows.Add(drow);
}
dtBind.AcceptChanges();
ViewState["dtBind"] = dtBind;
grid.DataSource = dtBind;
grid.DataBind();
}
}
if (e.CommandName == "Delete")
{
GridViewRow gvr = grid.NamingContainer as GridViewRow;
int row = int.Parse(e.CommandArgument.ToString());

DataRow[] drow = dt1.Select("Id=" + Id.ToString() + "AND DED_Id=" + row.ToString());
if (drow.Length > 0)
{
DataRow dr = drow[0];
//remove the rows from datatable
dt1.Rows.Remove(dr);
}
DataTable dtBind = dt1.Clone();
foreach (DataRow dr in dt1.Select("Id=" + Id.ToString()))
{
DataRow newdr = dtBind.NewRow();
newdr["DED_Id"] = dr["DED_Id"];
newdr["DED_Name"] = dr["DED_Name"];
newdr["Qty"] = dr["Qty"];
newdr["Id"] = dr["Id"];
dtBind.Rows.Add(newdr);
}
dtBind.AcceptChanges();
ViewState["dtBind"] = dtBind;

if (dtBind.Rows.Count == 0)
{
DataTable dtcol = (DataTable)ViewState["col"];
dtcol.Rows.Clear();
DataRow dr;
dr = dtcol.NewRow();
dtcol.Rows.Add(dr.ItemArray);
grid.DataSource = dtcol;
grid.DataBind();
grid.Rows[0].Visible = false;
grid.Rows[0].Controls.Clear();
}
else
{
grid.DataSource = dtBind;
grid.DataBind();
}
}
}
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: