How to show dx gridview total (summary item) on final page only? - asp.net

Below is my simplified gridview
Currently, the summary is shown on every page. But the client needs the total on the final page only. (Or even better having the total amount of the "page" on each page, and one total of all pages on the final page).
Any help is really appreciated :)
<dx:ASPxGridView ID="GrdMain" ClientInstanceName="GrdMain" runat="server"
KeyFieldName="AgentAccountSummaryId" Width="100%" AutoGenerateColumns="False">
<Columns>
<dx:GridViewDataTextColumn FieldName="Debit" VisibleIndex="6" UnboundType="Decimal">
<FooterCellStyle ForeColor="Brown" />
<PropertiesTextEdit DisplayFormatString="c0" />
</dx:GridViewDataTextColumn>
</Columns>
<Settings ShowFooter="True" />
<TotalSummary>
<dx:ASPxSummaryItem FieldName="Debit" SummaryType="Sum"/>
</TotalSummary>
</dx:ASPxGridView>
Update: Here is all I do in Code behind (in Page_Load):
GrdMain.SettingsPager.PageSize = 25;
GrdMain.ForceDataRowType(typeof(SomeTypeView));
GrdMain.DataSource = GetListOfSomeType();
GrdMain.DataBind();
I should also add that I am using DevExpress GridView

ASPX page :
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1"
ondatabound="GridView1_DataBound" PageSize="3" ShowFooter="True">
<Columns>
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False"
ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="fname" HeaderText="fname" SortExpression="fname" />
<asp:BoundField DataField="vote" HeaderText="vote" SortExpression="vote" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ProjectDB %>"
onselected="SqlDataSource1_Selected" SelectCommand="SELECT * FROM [tblA]" >
</asp:SqlDataSource>
Code behind :
decimal RowCount;
protected void GridView1_DataBound(object sender, EventArgs e)
{
int pageSize = GridView1.PageSize;
decimal totalPages = Math.Ceiling(RowCount / pageSize);
int TotalAllPage=0;
int TotalPerPage=0;
foreach (GridViewRow row in GridView1.Rows)
{
TotalPerPage += int.Parse( row.Cells[2].Text);
}
DataView dView = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
DataTable dTable = dView.ToTable();
foreach (DataRow item in dTable.Rows)
{
TotalAllPage += int.Parse(item[2].ToString());
}
if (GridView1.PageIndex + 1 == totalPages)
{
GridView1.FooterRow.Cells[2].Text = "Total all page:" + TotalAllPage;
}
else
{
GridView1.FooterRow.Cells[2].Text = "Total this page:" + TotalPerPage;
}
}
protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
RowCount = e.AffectedRows;
}

Related

How do i know which Buttons are triggered to perform specific task in Gridview

I have 2 buttons, one is called "Accept", which is used for updating of database while another is called "View", which is used for Redirecting. However, in GridView's SelectedIndexChanged, i wasnt able to Validate which buttons were click
so I have tried Using RowCommand for the "View" button and SelectedIndexChanged for "Accept" button. But RowCommand is triggering the "Accept" button in the SelectedIndexChanged event handler.
<asp:GridView ID="QgridView" AutoGenerateColumns="False"
CssClass="table table-bordered" AllowPaging="True" PageSize="6"
BackColor="White" BorderColor="Black" BorderStyle="Solid"
ForeColor="Black" GridLines="None" runat="server"
OnRowCommand="QgridView_RowCommand"
OnSelectedIndexChanged="QgridView_SelectedIndexChanged" >
<Columns>
<asp:TemplateField HeaderText="No">
<ItemTemplate>
<span>
<%#Container.DataItemIndex + 1%>
</span>
</ItemTemplate>
</asp:TemplateField>
<asp:ImageField HeaderText="Image" DataImageUrlField="coverimg" >
<ControlStyle CssClass="coverimage"/>
<ItemStyle HorizontalAlign="Center" />
</asp:ImageField>
<asp:BoundField HeaderText="Buyer" DataField="buyer" />
<asp:BoundField HeaderText="Item" DataField="item" />
<asp:BoundField HeaderText="Price offered" DataField="price" />
<asp:buttonfield buttontype="Button"
commandname="Accept"
text="Accept"/>
<asp:BoundField DataField="quoteid" HeaderText="quoteid" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" >
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="id" HeaderText="id" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol">
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="rtype" HeaderText="rtype" ItemStyle-
CssClass="hiddencol" HeaderStyle- CssClass="hiddencol">
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="seller" HeaderText="seller" ItemStyle-
CssClass="hiddencol" HeaderStyle-CssClass="hiddencol">
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:buttonfield buttontype="Button"
commandname="View"
text="View"/>
</Columns>
</asp:GridView>
// Behind COde page
protected void QgridView_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = QgridView.SelectedRow;
string seller = row.Cells[10].Text;
string item = row.Cells[4].Text;
string type = row.Cells[9].Text;
int id = Convert.ToInt32(row.Cells[8].Text);
int quoteid = Convert.ToInt32(row.Cells[7].Text);
productDAO productdao = new productDAO();
productdao.GridPush(quoteid, id)
}
protected void QgridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
Response.Redirect("ListingItems.aspx");
}
}
I want the "Accept" BUtton to perform the updating of database while the "View button to perform Response.Redirect. However, RowCommand does not fire and instead, it triggers the "Accept" button in SelectedIndexChanged. May i know how can perform the different task for each button?
[Gettting row data from GridView]
protected void QgridView_RowCommand(object sender,
GridViewCommandEventArgs e)
{
System.Diagnostics.Debug.WriteLine("onrowcommand");
if (e.CommandName == "View")
{
System.Diagnostics.Debug.WriteLine("ButtonView is clicked");
Response.Redirect("ListingItems.aspx");
}
else if (e.CommandName == "Accept")
{
System.Diagnostics.Debug.WriteLine("buttonAccept is clicked");
productDAO productdao = new productDAO();
//GridViewRow row = QgridView.SelectedRow;
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = QgridView.Rows[index];
string id = row.Cells[8].Text; //Returns me nothing
}
else
{
System.Diagnostics.Debug.WriteLine("no command name");
}
}
I think you are no need to check the rowcommand or onselected Index change event you can directly set button on click event. if you are using the inside your Gridview, then you should be able to register an event in your button code as:
<asp:Button runat="server" OnClick="YourclickEvent" />
For more details on event you should read this: https://www.codeproject.com/Articles/50540/GridView-Event-Handling
One Addition: if using row command then identify each button with command name and you can perform your task easily.
According to your code SelectedIndexChanged should be never fired (no select command).
RowCommand handler always fire first (before more specific handlers).
Look at sample working code.
.aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="CategoryID"
DataSourceID="sqlCategory"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnRowCommand="GridView1_RowCommand" AllowPaging="True">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="Category Name" SortExpression="CategoryName" />
<asp:ButtonField ButtonType="Button" CommandName="Accept" HeaderText="Accept" ShowHeader="True" Text="Accept" />
<asp:ButtonField ButtonType="Button" CommandName="View" HeaderText="View" ShowHeader="True" Text="View" />
<%-- Use HyperLinkField instead of ButtonField --%>
<asp:HyperLinkField DataNavigateUrlFields="CategoryID" DataNavigateUrlFormatString="category.aspx?categoryid={0}" DataTextField="CategoryName" DataTextFormatString="View {0}" HeaderText="Direct View" />
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
</Columns>
</asp:GridView>
<%-- Data from NorthWind learning DB --%>
<asp:SqlDataSource ID="sqlCategory" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnection %>"
SelectCommand="SELECT CategoryID, CategoryName FROM Categories"
UpdateCommand="update categories set categoryName=#CategoryName where CategoryID=#CategoryID">
<UpdateParameters>
<asp:Parameter Name="CategoryID" Type="Int32" />
<asp:Parameter Name="CategoryName" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
.aspx.cs
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
Trace.Write("GridView1_SelectedIndexChanged");// fired by "select" command after RowCommand finished
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Trace.Write("GridView1_RowCommand");
//
if (e.CommandName == "Accept")
{
var categoryId = (int)GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)].Value;//e.CommandArgument is display index
Trace.Write(e.CommandName + ": " + e.CommandArgument + " : " + categoryId.ToString());
}
else if (e.CommandName == "View")
{
Trace.Write("View " + e.CommandArgument);
}
}

Get files names from AjaxFileUpload Control on button click

Please help with these ;
I have a gridview with AjaxFileupload in the Itemtemplate. After populating the gridview and uploading files using the AjaxFileUpload in each row. I need to read through the gridview and get the filename at bujtton click. Please find below the codes
<div>
<asp:GridView ID="grdView_Requirement" runat="server" AutoGenerateColumns="False" Font-Names="Segoe UI" Font-Size="12px">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:TemplateField HeaderText="Upload File">
<ItemTemplate>
<asp:AjaxFileUpload ID="AjaxFileUploadNew" runat="server" Font-Names="Segoe
UI" Font-Size="12px" MaximumNumberOfFiles="1" Width="388px" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
</Columns>
<FooterStyle BackColor="#5D7B9D" ForeColor="#333333" />
<HeaderStyle BackColor="#D7D9E5" ForeColor="#333333" />
<RowStyle BackColor="#FFFFFF" ForeColor="#333333" />
</asp:GridView>
</div>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
Upload code
protected void AjaxFileUploadNew_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string strLongFilePath = e.FileName;
string strFileExtension = System.IO.Path.GetExtension(strLongFilePath);
char[] ch = new char[] { '\\' };
string[] strPath = strLongFilePath.Split(ch);
string strInternalFileName = DateTime.Now.ToFileTime().ToString() + strFileExtension;
string strDestPath = Server.MapPath("~/UploaderTemp/");
AjaxFileUploadNew.SaveAs(#strDestPath + strInternalFileName);
//Save path, filename to database here
}
Kindly help in getting the uploaded file name in the event below
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in grdView_Requirement.Rows)
{
//for bound field
string str = row.Cells[0].Text.ToString();
//for templated control
AjaxControlToolkit.AjaxFileUpload tb = row.FindControl("AjaxFileUploadNew") as
AjaxControlToolkit.AjaxFileUpload;
}
}
Kindly help resolve or give better ways of implementing to achieve success.

how to dynamically add button in gridview cell

gridview cannot add an 'approve' button in gridview,can someone can help me thanks
http://i260.photobucket.com/albums/ii8/elvenchan2/rowAdd.png
behind code
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow dr in GridView2.Rows)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btn = new Button();
btn.Text = "Approve";
btn.ID = "Approve";
btn.Click += new EventHandler(Approve_Click);
if (dr.Cells[1].Text == "1")
{
dr.Cells[10].Controls.Add((Control)btn);
}
}
}
}
u must add a 10th cell at first
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow dr in GridView2.Rows)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btn = new Button();
btn.Text = "Approve";
btn.ID = "Approve";
btn.Click += new EventHandler(Approve_Click);
if (dr.Cells[1].Text == "1")
{
//Declare the bound field and allocate memory for the bound field.
ButtonField btnRent = new ButtonField();
//Initalize the DataField value.
btn.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
btn.CommandName = "Button";
btn.ButtonType = ButtonType.Button;
btn.Text = "Rent";
btn.Visible = true;
//Add the newly created bound field to the GridView.
GridView2.Columns.Add(btn);
}
}
}
}
Since there is no criteria for creating the button, why not just make a TemplateField in your GridView markup and wire up a click handler or CommandName for the button, like this:
<asp:GridView id="GridView1" runat="server"
OnRowCommand="GridView1_RowCommand">
<Columns>
...
<asp:TemplateField>
<ItemTemplate>
<asp:Button id="ButtonApprove" runat="server"
CommandName="approve" Text="Approve" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now in your code-behind, you can handle each individual approve button click, like this:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "approve")
{
// Do approval logic here
}
}
You can try it:
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState != DataControlRowState.Edit)
{
PlaceHolder ph = (PlaceHolder)e.Row.FindControl("PlaceHolder1");
Button b1 = new Button();
b1.ID = "Approve";
b1.Text = "Approve"
ph.Controls.Add(b1);
}
}
Of course, you should add a placeholder in the html template. like
<ItemTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
Button add here..
</asp:PlaceHolder>
</ItemTemplate>
Design
<asp:GridView ID="viewThemeTypeAssociationsGridView" runat="server" AutoGenerateColumns="False"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
CellPadding="3" CellSpacing="2"
OnRowDataBound="viewThemeTypeAssociationsGridView_RowDataBound"
DataSourceID="Sql_New" >
<Columns>
<asp:BoundField DataField="id" HeaderText="id" SortExpression="id"
InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:TemplateField HeaderText ="New Column" >
<ItemTemplate >
<asp:Button ID="btnnew" runat ="server" Visible ="false" ></asp:Button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
<asp:SqlDataSource ID="Sql_New" runat="server"
ConnectionString="<%$ ConnectionStrings:EmployeeConnectionString %>"
SelectCommand="SELECT * FROM [tblnew]"></asp:SqlDataSource>
Code
protected void viewThemeTypeAssociationsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells[2].Text == " ")
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btnnew = (Button)e.Row.FindControl("btnnew");
btnnew.Visible = true;
}
}
}

asp can't detect the checked item in datagridview

I have a gridview with ckeck column,my user can select the item via checked box so i add a checkbox column to my gridview:
<asp:GridView ID="taminkonandeh" runat="server" CssClass="gv-list-company-col-edit" ShowHeaderWhenEmpty="True" AutoGenerateColumns="False" EnableModelValidation="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ChTaminKonande" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="شماره " DataField="companyid" >
<HeaderStyle CssClass="gv-list-company-header" />
<ItemStyle CssClass="gv-list-company-col" />
</asp:BoundField>
<asp:BoundField HeaderText="نام شرکت " DataField="companyname">
<HeaderStyle CssClass="gv-list-company-header" />
<ItemStyle CssClass="gv-list-company-col" />
</asp:BoundField>
<asp:BoundField HeaderText="شماره ثبت " DataField="registrationNumber" >
<HeaderStyle CssClass="gv-list-company-header" />
<ItemStyle CssClass="gv-list-company-col" />
</asp:BoundField>
<asp:BoundField HeaderText="شماره اقتصادی" DataField="noEconomic" >
<HeaderStyle CssClass="gv-list-company-header" />
<ItemStyle CssClass="gv-list-company-col" />
</asp:BoundField>
</Columns>
<HeaderStyle CssClass="gv-list-company-header" />
<RowStyle CssClass="gv-list-company-row"/>
</asp:GridView>
and my code behind is :
for (int i = 0; i < taminkonandeh.Rows.Count; i++)
{
CheckBox chinvi = (CheckBox)taminkonandeh.Rows[i].FindControl("ChTaminKonande");
if (chinvi != null)
{
if (chinvi.Checked)
{
Count++;
comid = taminkonandeh.Rows[i].Cells[1].Text;
tblAnnouncePriceByCompany objanno = new tblAnnouncePriceByCompany();
objanno.letterId = objletter.letterId.ToString();
objanno.companyId = comid;
objanno.tenderId = Session["letterTenderId"].ToString();
db1.tblAnnouncePriceByCompanies.InsertOnSubmit(objanno);
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "myalert",
"alert('تامین کننده ای انتخاب نشده است ')", true);
return;
}
}
but "chinvi.Checked" condition is always false and i can't detect which checkboxs are selected.
This situation happens when you bind the gridview in pageload, and each postback rebinds it, removes posted value like this:
protected void Page_Load(object sender, EventArgs e)
{
//Code to get datasource
taminkonandeh.DataSource = myDataSource;
taminkonandeh.DataBind();
}
You need to change it to :
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Code to get datasource
taminkonandeh.DataSource = myDataSource;
taminkonandeh.DataBind();
}
}

Query regarding the nested grid views in asp.net/C#

I have defined a nested grid view in the following way.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" GridLines="None">
<Columns>
<asp:BoundField DataField="Date Of Transaction" HeaderText="Date Of Transaction"
SortExpression="Date Of Transaction" />
<asp:BoundField DataField="Invoice Number" HeaderText="Invoice Number" SortExpression="Invoice Number" />
<asp:BoundField DataField="totalAmount" HeaderText="totalAmount" ReadOnly="True"
SortExpression="totalAmount" />
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="gridView2" runat="server" HorizontalAlign="Left" ShowHeader="false" GridLines="None" OnRowDataBound="gridView2_RowDataBound">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Button ID="Btn1" runat="server" Text="Download" OnClick="Btn1_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ComponentDBConnectionString %>"
SelectCommand="SelectUserPreviousHistory" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="XYZZ" Name="userName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
The screenshot of the output is here. As you can see i have a "Download" button in each row of the child gridview (i.e., gridView2) but I want the download button to be last column but .net is rendering it to be the first column.
How can I do it?
More over gridview2 datasource is arraylist. Here is the code
gridView2.DataSource = titlesArrayList;
gridView2.DataBind();
Please help me
Thanks in anticipation
Why don't you simply add a Label before the Donwload-Button in the ItemTemplate? You could set the Label's Text in RowDataBound(gridView2_DataBound).
Edit: to show the header columns of the nested gridview in the header of the outer gridview, you could set ShowHeader="false" in the inner grid and use a HeaderTemplate with two labels for "Software Titles" and "Download here" and appropriate CSS-Styles to fit to the inner grid.
Edit:
Here is a working test-page. Pick the parts you didn't understand:
aspx:
<asp:GridView ID="GrdTransaction" runat="server" OnRowDataBound="GrdTransaction_RowDataBound" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="DateOfTransaction" HeaderText="Date Of Transaction"
SortExpression="DateOfTransaction" />
<asp:TemplateField>
<HeaderTemplate>
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tr>
<td><asp:Label ID="LblFileNameHeader" Text="File-Name" runat="server" /></td><td><asp:Label ID="LblDownloadHeader" Text="Download file" runat="server" /></td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<asp:GridView ID="GrdDocument" runat="server" ShowHeader="false" GridLines="None" AutoGenerateColumns="false"
OnRowCommand="GrdDocument_RowCommand" OnRowDataBound="GrdDocument_RowDataBound">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Label ID="LblFileName" Text='<%# Eval("Doc")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Button ID="BtnDownload" runat="server" CommandArgument='<%# Eval("Doc")%>' CommandName="Download" Text="Download" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Codebehind(converted from vb.net to c#):
public class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
this.GrdTransaction.DataSource = GetOuterGridSource();
this.GrdTransaction.DataBind();
}
}
private DataTable GetOuterGridSource()
{
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("DateOfTransaction", typeof(DateTime)));
DataRow row = tbl.NewRow();
row["ID"] = 1;
row["DateOfTransaction"] = System.DateTime.Now;
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["DateOfTransaction"] = System.DateTime.Now;
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["DateOfTransaction"] = System.DateTime.Now;
tbl.Rows.Add(row);
return tbl;
}
private DataTable GetNestedGridSource()
{
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("Doc", typeof(string)));
DataRow row = tbl.NewRow();
row["ID"] = 1;
row["Doc"] = "Smart Defrag";
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["Doc"] = "Visio Viewer";
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["Doc"] = "Rapid Typing";
tbl.Rows.Add(row);
return tbl;
}
protected void GrdTransaction_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
dynamic row = ((DataRowView)e.Row.DataItem).Row;
dynamic GrdDocument = (GridView)e.Row.FindControl("GrdDocument");
GrdDocument.DataSource = GetNestedGridSource();
GrdDocument.DataBind();
GrdDocument.RowCommand += GrdDocument_RowCommand;
}
}
protected void GrdDocument_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
dynamic row = ((DataRowView)e.Row.DataItem).Row;
dynamic LblFileName = (Label)e.Row.FindControl("LblFileName");
LblFileName.Text = row("Doc").ToString;
}
}
protected void GrdDocument_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName == "Download") {
dynamic docName = e.CommandArgument.ToString();
}
}
public WebForm1()
{
Load += Page_Load;
}
}
I have set the LblFileName's Text poperty in GrdDocument_RowDataBound. That is redundant because i've always used eval on the aspx-page. I wanted to show both ways for the sake of completeness.
This is result:
in your gridView2, set AutoGenerateColumns="False" and add a asp:BoundField before the asp:TemplateField
Are you sure there is no missing code in your snippet?
<asp:GridView ID="gridView2" runat="server" HorizontalAlign="Left" ShowHeader="false" GridLines="None" OnRowDataBound="gridView2_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="" DataField="ToString" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Button ID="Btn1" runat="server" Text="Download" OnClick="Btn1_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Resources