Showing posts with label Gridview. Show all posts
Showing posts with label Gridview. Show all posts

Simple Nested Gridview In ASP.NET

2011-05-14

Here is the code for creating Nested gridview in asp.net, one can do this easily in asp.net. I have seen third party controls like Infragistics & DevExpress control kit where they provide this feature in their grid controls. Although we cannot compare this grid with thiers, but this one is sufficient for a normal user scenario requirements
Example of Buisness Requirement where Nested GridView should be displayed:
In Estimation area there is a requirement of knowing the rates of all the contractors for a given material , then it would be good if our grid can show like as in given below figures.


HTML Code
-------------
<table style="width:100%;height:100%;">

<tr>

<td>

<asp:GridView ID="grdOuterGridView" runat="server" AllowPaging="True"

AutoGenerateColumns="False" DataKeyNames="MaterialID"

onrowdatabound="grdOuterGridView_RowDataBound" CellPadding="4"

ForeColor="#333333" GridLines="None">

<AlternatingRowStyle BackColor="White" />

<Columns>

<asp:TemplateField>

<ItemTemplate>

<a href="javascript:switchViews('div<%# Eval("MaterialID") %>');">

<img id="imgdiv<%# Eval("MaterialID") %>" title="Click to show/hide orders" border="0" src="images/rightarrow.png" width="15px" />

</a>

</ItemTemplate>

</asp:TemplateField>



<asp:BoundField HeaderText="Material" DataField="Material" />

<asp:BoundField HeaderText="Code" DataField="MaterialCode"/>

<asp:TemplateField>

<ItemTemplate>

</td></tr>

<tr>

<td colspan="100%">

<div id="div<%# Eval("MaterialID") %>" style="display:none;position:relative;left:25px;" >

<asp:GridView ID="grdInnerGridView" runat="server" Width="80%"

AutoGenerateColumns="false" DataKeyNames="RateID"

EmptyDataText="No rates available from the contractors." >

<Columns>

<asp:BoundField HeaderText="Contractor Name" DataField="ContractorName" />

<asp:BoundField HeaderText="Rate" DataField="Rate" />





</Columns>

</asp:GridView>

</div>

</td>

</tr>



</ItemTemplate>



</asp:TemplateField>

</Columns>

<EditRowStyle BackColor="#2461BF" />

<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />

<RowStyle BackColor="#EFF3FB" />

<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />

<SortedAscendingCellStyle BackColor="#F5F7FB" />

<SortedAscendingHeaderStyle BackColor="#6D95E1" />

<SortedDescendingCellStyle BackColor="#E9EBEF" />

<SortedDescendingHeaderStyle BackColor="#4870BE" />

</asp:GridView>

</td>

</tr>

</table>














C# Code
------------
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

using System.Data;



namespace MinimizeMaximizeTab

{

public partial class NestedGridview : System.Web.UI.Page

{

SqlConnection objConnection = new SqlConnection("Integrated security=false;user id='sa';pwd='beta';database='ASIF_DB'");

SqlCommand objCommand = new SqlCommand();



protected void Page_Load(object sender, EventArgs e)

{

objCommand.Connection = objConnection;

FillOuterGrid();

}



protected void grdOuterGridView_RowDataBound(object sender, GridViewRowEventArgs e)

{

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

{

int materialID = (int)grdOuterGridView.DataKeys[e.Row.RowIndex].Values["MaterialID"];

GridView innerGridView = (GridView)e.Row.FindControl("grdInnerGridView");

FillInnerGrid(materialID, innerGridView);

}



}



private void FillOuterGrid()

{

objCommand.CommandText = "SELECT MaterialID,Material,MaterialCode FROM Materials";

SqlDataAdapter objAdap = new SqlDataAdapter(objCommand);

DataTable dtMaterials=new DataTable();

objConnection.Open();

objAdap.Fill(dtMaterials);

objConnection.Close();

grdOuterGridView.DataSource = dtMaterials;

grdOuterGridView.DataBind();

}



private void FillInnerGrid(int materialID, GridView grdInnerGridView)

{

objCommand.CommandText = "SELECT RateID,ContractorName,Rate from Contractors INNER JOIN ContractorRates on Contractors.ContractorID = ContractorRates.ContractorID where MaterialID="+ materialID;

SqlDataAdapter objAdap = new SqlDataAdapter(objCommand);

DataTable dtContractorRates = new DataTable();

objConnection.Open();

objAdap.Fill(dtContractorRates);

objConnection.Close();

grdInnerGridView.DataSource = dtContractorRates;

grdInnerGridView.DataBind();

}





}

}




Javascript Code

---------------------



function switchViews(obj)

{

var div = document.getElementById(obj);

var img = document.getElementById('img' + obj);



if (div.style.display=="none")

{

div.style.display = "inline";

img.src="images/downarrow.png" ;

img.title = "Close to view other materials";

}

else

{

div.style.display = "none";

img.src="images/rightarrow.png" ;

img.title = "Expand to view other contracto rates";

}

}
Summary -------- 1. Create a template & place a gridview in it 2. Fill the gridview at the row databound of parent gridview 3. Create a tag a to call javascript function which passes the id of the div tag inside which inner gridview is placed at the first template column of parent grid. 4. On calling javascript function change the display from inline/block to none or none to inline/block & also change the image too

How to set a constant width for a gridview column.

2011-04-24

In one of my pages I wanted to show Error Log stored in the database to a gridview.
In that there is Error Descritpion column which has got very large text. I only wanted to display the beginning of the Error Description. On selecting the particular error description a pop up page comes & display the description in detail. So how can we set the Error Description column a constant width & text to be displayed only at the beginning.

1. Create a template column place a link button inside a table
2. Set the width of the LinkButton
3. Set Style property overflow:hidden
4. Set the ItemStyle for this template & define width & set Wrap=false

that is like this


<asp:TemplateField>

<HeaderTemplate>Product Description</HeaderTemplate>



<ItemTemplate>



<table>

<tr>

<td>

<asp:LinkButton id="lnkProductDescription" runat="server" Text='<%# Eval("ProductDescription") %>' Width="150px" style="overflow:hidden;"></asp:LinkButton>

</td>

</tr>

</table>



</ItemTemplate>

<%--For making the Wrap of the column to be disabled --%>

<ItemStyle Width="150px" Wrap="false" />



</asp:TemplateField>













Setting More than 1 DataKeys In GridView

2010-07-05

<asp:GridView ID="gvwSiteVisitDetails" runat="server" Width="100%"
AllowPaging="True" DataKeyNames="GATExecutionDepartmentSiteVisitID,GATSiteVisitID"
onrowdatabound="gvwSiteVisitDetails_RowDataBound" onpageindexchanging="gvwSiteVisitDetails_PageIndexChanging"
>
<Columns>
<asp:BoundField HeaderText="GATExecutionDepartmentSiteVisitID" Visible="False" DataField="GATExecutionDepartmentSiteVisitID" />
<asp:BoundField HeaderText="GATSiteVisitID" Visible="False" DataField="GATSiteVisitID" />
</Columns>
<EmptyDataTemplate>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td style="text-align: center; height: 16px;">
<asp:Label ID="lblSiteVisit" runat="server" Font-Bold="False" SkinID="NoRecords"
Text="No site visit details are loaded" Width="100%"></asp:Label>
</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:GridView>


How to display serial no. In Gridview

<asp:Label ID="lblSlno" runat="server" Text='<%# (gvwDocuments.PageSize * gvwDocuments.PageIndex) + Container.DisplayIndex + 1 %>'></asp:Label>


How to access GridView DataKey values

2010-06-21

int pKey = (int)gvwSiteVisitDetails.DataKeys[gvRow.RowIndex].Values["GATExecutionDepartmentSiteVisitID"];

Adding Dynamic columns to gridview

2010-05-23

private void FillGrid(int BOQTenderID)
{
try
{
IBOQSubcontractRateComparisonManager objManager = TBDBusinessFactory.CreateBOQSubcontractRateComparisonManager();
List lst = objManager.GetBOQSubcontractRateComparison(BOQTenderID);
Session["SubcontractorActivityRatesAgainstBOQByAllSubContractors"] = lst;
AddNewColumnsToGrid(lst);
gvSubContractorActivitiesRates.DataSource = lst;
gvSubContractorActivitiesRates.DataBind();
SaveViewState();
}
catch (Exception ex)
{
}
}

private void AddNewColumnsToGrid(List lst)
{
try
{
BoundField column = null;
int noOfNewColoumnsToAdd = 0;
int totalColumnCount = gvSubContractorActivitiesRates.Columns.Count;
//Remove all columns
for (int i = 1; i <= totalColumnCount; i++)
{
gvSubContractorActivitiesRates.Columns.RemoveAt(totalColumnCount - i);
}
//Add fixed columns(fixed columns = 2)([ESTSubContractActivityID,SubContractActivity]-single column &
//Select Lowest Rate
column = new BoundField();
column.HeaderText = "SubContractActivity";
gvSubContractorActivitiesRates.Columns.Add(column);
column = new BoundField();
column.HeaderText = "Select Lowest Rate";
gvSubContractorActivitiesRates.Columns.Add(column);
//==find the no of columns to add dynamically where no of dynamic columns = no of subcontracotrs==//
List lstContractorsAlreadyAdded = new List();
foreach (SCTActivitiesAndRatesByContractorsInfo info in lst)
{
foreach (TBDBOQSubContractRateComparisonGetInfo x in info.LstContractorWithRate)
{
if (!lstContractorsAlreadyAdded.Exists(k => k.ContractorShortName == x.ContractorShortName))
{
noOfNewColoumnsToAdd++;
lstContractorsAlreadyAdded.Add(x);
}
}
}
for (int i = 1; i <= noOfNewColoumnsToAdd; i++)
{
column = new BoundField();
column.HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
column.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
gvSubContractorActivitiesRates.Columns.Add(column);
}
//Adding Selected Rate Column as the last column
column = new BoundField();
column.HeaderText = "Selected Rate";
column.HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
column.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
gvSubContractorActivitiesRates.Columns.Add(column);
}
catch (Exception ex)
{
}
}
///
/// Adding controls to the newly created columns
///
///
///

protected void gvSubContractorActivitiesRates_RowCreated(object sender, GridViewRowEventArgs e)
{
List lst = (List)Session["SubcontractorActivityRatesAgainstBOQByAllSubContractors"];
List lstActivitiesAlreadyAdded = null;
List lstContractorsAlreadyAdded = null;
if (Session["activitiesAlreadyAdded"] != null)
{
lstActivitiesAlreadyAdded = (List)Session["activitiesAlreadyAdded"];
}
else
{
lstActivitiesAlreadyAdded = new List();
}
try
{
        #region HEADER ROW
if (e.Row.RowType == DataControlRowType.Header)
{
lstContractorsAlreadyAdded = new List();
int columnIndex = 1;
//Adding checkbox to the header of the 2nd column "Select Lowest Rate"
CheckBox chkSelectAllLowest = new CheckBox();
chkSelectAllLowest.ID = string.Format("chkSelectAllLowest{0}", columnIndex);
chkSelectAllLowest.Text = "Select Lowest Rate";
//Adding the newly created controls to header row
e.Row.Cells[columnIndex].Controls.Add(chkSelectAllLowest);
//Dynamic no of columns to be added from 2 onwards
columnIndex = 2;
foreach (SCTActivitiesAndRatesByContractorsInfo info in lst)
{
foreach (TBDBOQSubContractRateComparisonGetInfo x in info.LstContractorWithRate)
{
if (!lstContractorsAlreadyAdded.Exists(k => k.ContractorShortName == x.ContractorShortName))
{
Label lblSubContractor = new Label();
CheckBox chkSelectContractor = new CheckBox();
HiddenField hdnSCTContractorID = new HiddenField();
//Setting IDs to the newly created controls
lblSubContractor.ID = string.Format("lblSubContractor{0}", columnIndex);
chkSelectContractor.ID = string.Format("chkSelectContractor{0}", columnIndex);
hdnSCTContractorID.ID = string.Format("hdnSCTContractorID{0}", columnIndex);
//Setting Text values to the newly created controls
lblSubContractor.Text = x.ContractorShortName;
hdnSCTContractorID.Value = x.SCTContractorID.ToString();
//Adding the newly created controls to header row
e.Row.Cells[columnIndex].Controls.Add(chkSelectContractor);
e.Row.Cells[columnIndex].Controls.Add(lblSubContractor);
e.Row.Cells[columnIndex].Controls.Add(hdnSCTContractorID);
columnIndex++;
lstContractorsAlreadyAdded.Add(x);
}
}
}
}
#endregion


#region DATAROW
if (e.Row.RowType == DataControlRowType.DataRow)
{
lstContractorsAlreadyAdded = new List();
int columnIndex = 0;
//Adding control to first column [ESTSubContractActivityID,SubContractActivity &
// TBDBOQSubcontractRateComparisonID]-single column
Label lblSubContractActivity = new Label();
lblSubContractActivity.ID = string.Format("lblSubContractActivity{0}", columnIndex);
e.Row.Cells[columnIndex].Controls.Add(lblSubContractActivity);
HiddenField hdnESTSubContractActivityID = new HiddenField();
hdnESTSubContractActivityID.ID = string.Format("hdnESTSubContractActivityID{0}", columnIndex);
e.Row.Cells[columnIndex].Controls.Add(hdnESTSubContractActivityID);
//Adding TBDBOQSubcontractRateComparisonID to the first column
HiddenField hdnTBDBOQSubcontractRateComparisonID = new HiddenField();
hdnTBDBOQSubcontractRateComparisonID.ID = string.Format("hdnTBDBOQSubcontractRateComparisonID{0}", columnIndex);
e.Row.Cells[columnIndex].Controls.Add(hdnTBDBOQSubcontractRateComparisonID);
columnIndex = 2;
foreach (SCTActivitiesAndRatesByContractorsInfo info in lst)
{
if (!lstActivitiesAlreadyAdded.Exists(k => k.ESTSubContractActivityID == info.ESTSubContractActivityID))
{
foreach (TBDBOQSubContractRateComparisonGetInfo x in info.LstContractorWithRate)
{
if (!lstContractorsAlreadyAdded.Exists(k => k.ContractorShortName == x.ContractorShortName))
{
lstActivitiesAlreadyAdded.Add(info);
HiddenField hdnTBDBOQSubContractRateID = new HiddenField();
QuadraQuantityTextBox qqtyRateOfContractorForActivity = new QuadraQuantityTextBox();
//Setting IDs to the newly created controls
hdnTBDBOQSubContractRateID.ID = string.Format("hdnTBDBOQSubContractRateID{0}", columnIndex);
qqtyRateOfContractorForActivity.ID = string.Format("qqtyRateOfContractorForActivity{0}", columnIndex);
//Setting Enable property of Rate field to false
qqtyRateOfContractorForActivity.Enabled = false;
//Adding the newly created controls to the datarow
e.Row.Cells[columnIndex].Controls.Add(hdnTBDBOQSubContractRateID);
e.Row.Cells[columnIndex].Controls.Add(qqtyRateOfContractorForActivity);
columnIndex++;
lstContractorsAlreadyAdded.Add(x);
}
}
}
}
//columnIndex += gvSubContractorActivitiesRates.Columns.Count - 3;//Subtract first & second columns
//Adding controls to the last column "Selected Rate"
QuadraQuantityTextBox qqtytxtSelectedRate = new QuadraQuantityTextBox();
qqtytxtSelectedRate.ID = string.Format("qqtytxtSelectedRate{0}", columnIndex);
qqtytxtSelectedRate.Enabled = false;
e.Row.Cells[columnIndex].Controls.Add(qqtytxtSelectedRate);
//This hidden field is set to the last column as Value from QuadraQuantityTextBox could not read 
//from server side when the value is set at from client side!!!(work around)
HiddenField hdnSelectedRate = new HiddenField();
hdnSelectedRate.ID = string.Format("hdnSelectedRate{0}", columnIndex);
e.Row.Cells[columnIndex].Controls.Add(hdnSelectedRate);
//Keeping the lstActivitiesAlreadyAdded to the session
Session["activitiesAlreadyAdded"] = lstActivitiesAlreadyAdded;
}
#endregion
}
catch (Exception ex)
{
}
}
///
/// Setting values to the cells of the rows
///
///
///
protected void gvSubContractorActivitiesRates_RowDataBound(object sender, GridView
{
try
{
SCTActivitiesAndRatesByContractorsInfo bindingInfo = null;
if (e.Row.RowType == DataControlRowType.Header)
{
int columnIndex = 1;
CheckBox chkSelectAllLowest = (CheckBox)e.Row.FindControl("chkSelectAll");
if (chkSelectAllLowest.ClientID == hdnSelectedHeaderCheckBoxID.Value)
{
if (hdnPreviousPageCheckBoxHeaderState.Value == "checkedState")
chkSelectAllLowest.Checked = true;
else if (hdnPreviousPageCheckBoxHeaderState.Value == "unCheckedSta
chkSelectAllLowest.Checked = false;
string chkSelectAllLowestClientID = "document.getElementById("" +
Page.ClientScript.RegisterStartupScript(this.GetType(), "keyExecut
}
chkSelectAllLowest.Attributes.Add("onclick", "CheckOrUncheckLowestRate
//Dynamic no of columns starts from 2 onwards
columnIndex = 2;
List lst = (List< td=""> <>
List lstContractorsAlreadyAdde
foreach (SCTActivitiesAndRatesByContractorsInfo info in lst)
{
foreach (TBDBOQSubContractRateComparisonGetInfo x in info.LstContr
{
if (!lstContractorsAlreadyAdded.Exists(k => k.ContractorShortN
{
//===Get Controls in the header of each subcontractors===/
HiddenField hdnSCTContractorID = (HiddenField)e.Row.FindCo
CheckBox chkSelectContractor = (CheckBox)e.Row.FindControl
if (chkSelectContractor.ClientID == hdnSelectedHeaderCheck
{
if (hdnPreviousPageCheckBoxHeaderState.Value == "check
chkSelectContractor.Checked = true;
else if (hdnPreviousPageCheckBoxHeaderState.Value == "
chkSelectContractor.Checked = false;
string chkSelectContractorClientID = "document.getElem
Page.ClientScript.RegisterStartupScript(this.GetType()
}
//====Set Javascript function on selecting this subcontrac
chkSelectContractor.Attributes.Add("onclick", "SetRatesOfC
columnIndex++;
lstContractorsAlreadyAdded.Add(x);
}
}
}
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
int columnIndex = 0;
bindingInfo = (SCTActivitiesAndRatesByContractorsInfo)e.Row.DataItem;
//Binding values to first column [ESTSubContractActivityID,SubContract
// TBDBOQSubcontractRateComparisonID]
HiddenField hdnESTSubContractActivityID = (HiddenField)e.Row.FindContr
hdnESTSubContractActivityID.Value = bindingInfo.ESTSubContractActivity
Label lblSubContractActivity = (Label)e.Row.FindControl("lblSubContrac
lblSubContractActivity.Text = bindingInfo.SubContractActivity;
HiddenField hdnTBDBOQSubcontractRateComparisonID = (HiddenField)e.Row.
hdnTBDBOQSubcontractRateComparisonID.Value = bindingInfo.TBDBOQSubcont
columnIndex = 2;//From 2nd column onwards dynamic columns
foreach (TBDBOQSubContractRateComparisonGetInfo x in bindingInfo.LstCo
{
HiddenField hdnTBDBOQSubContractRateID = (HiddenField)e.Row.FindCo
QuadraQuantityTextBox qqtyRateOfContractorForActivity = (QuadraQua
hdnTBDBOQSubContractRateID.Value = x.TBDBOQSubContractRateID.ToStr
qqtyRateOfContractorForActivity.Text = GetFormattedRate(x.Contract
columnIndex++;
}
//columnIndex += bindingInfo.LstContractorWithRate.Count;
//Setting values for the controls in the last column
QuadraQuantityTextBox qqtytxtSelectedRate = (QuadraQuantityTextBox)e.R
qqtytxtSelectedRate.Text = GetFormattedRate(bindingInfo.Rate);
HiddenField hdnSelectedRate = (HiddenField)e.Row.FindControl("hdnSelec
hdnSelectedRate.Value = GetFormattedRate(bindingInfo.Rate);
}
}
catch (Exception ex)
{
}
}
protected void gvSubContractorActivitiesRates_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
gvSubContractorActivitiesRates.PageIndex = e.NewPageIndex;
FillGrid(int.Parse(ddlTenderNo.SelectedValue));
}
catch (Exception ex)
{
}
}