Gridview pagination. "Download All" Only downloads current page - c#

I have a grid view showing product images:
<form id="form1" runat="server">
<asp:Button ID="btnDownload" runat="server" CssClass="dist-down-button" Text="Download Selected" OnClick="DownloadFiles" />
<asp:Button ID="Button1" runat="server" CssClass="dist-down-button" Text="Download All" OnClick="DownloadAll" />
<asp:GridView ID="GridView1" runat="server" CssClass="mydatagrid" PagerStyle-CssClass="pager" HeaderStyle-CssClass="header" RowStyle-CssClass="rows" AllowPaging="True" OnPageIndexChanging="datagrid_PageIndexChanging" AutoGenerateColumns="false" EmptyDataText="No files available">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
<asp:Label ID="lblFilePath" runat="server" Text='<%# Eval("Value") %>' Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Text" HeaderText="Image Name" />
</Columns>
</asp:GridView>
</form>
Binding function: (matches all the files in the products folder with the product images list from database and show matching products)
protected void BindData()
{
images = GetProductImages();
string[] filePaths = Directory.GetFiles(Server.MapPath("~/upload/Products/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
if (images.IndexOf(Path.GetFileName(filePath)) > -1)
{
files.Add(new ListItem(Path.GetFileName(filePath), filePath));
}
}
GridView1.DataSource = files;
GridView1.DataBind();
}
protected void datagrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
Download All function: (look for the gridview list and download all the files listed)
protected void DownloadAll(object sender, EventArgs e)
{
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddDirectoryByName(ProductUrl);
foreach (GridViewRow row in GridView1.Rows)
{
string filePath = (row.FindControl("lblFilePath") as Label).Text;
zip.AddFile(filePath, ProductUrl);
}
Response.Clear();
Response.BufferOutput = false;
string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
zip.Save(Response.OutputStream);
Response.End();
}
}
When I click on Download All button it was downloading all the files correctly. BUT after I added the pagination the download all is now only downloading the current page.
Note: The checkbox is for selected download function. As you see I am not looking for checkboxes checked in the DownloadAll function.
Does anyone know why is this happening eventhough I am not looking for any checkbox in my function?

You could turn off paging and re-binding the GridView before exporting:
protected void DownloadAll(object sender, EventArgs e)
{
GridView1.AllowPaging = false;
BindData();
// ... your code
GridView1.AllowPaging = true;
BindData();
}

In Download All function, you have clearly writing that...take file path
only from gridview.. After the pagination...so it only take Current
Page Gridview data...not pickup all the data..
foreach (GridViewRow row in GridView1.Rows)
{
string filePath = (row.FindControl("lblFilePath") as Label).Text;
zip.AddFile(filePath, ProductUrl);
}
Solution:-
So, Whenever you binding the Gridview that time hold all data in
ViewState..
gridView.DataSource = dt;
gridView.DataBind();
ViewState["DownLoadGridData"]=dt as DataTable;
DataTable dt = ViewState["DownLoadGridData"] as DataTable;
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
if (row[FilePath] != null) // This will check the null values also (if you want to check).
{
// then add filepath
string filePath = row[FilePath].ToString();
zip.AddFile(filePath, ProductUrl);
}
}
}
Note:- you can develop your own logic also

Related

How to find child view outside rowdatabound

I have tow grid views master grid is gridpurchase and child grid is gvItems
I am trying to hide some columns in gvItems when exporting the grids to excel file.
i have tried the below code but it didn't work
Exporting code
protected void btnexcel_Click(object sender, EventArgs e)
{
gridpurchase.DataSource = po.GetPurchaseOrders();
gridpurchase.DataBind();
GridView gvItems = gridpurchase.FindControl("gvItems") as GridView;
gvItems.Columns[0].Visible = false;
gridpurchase.GridLines = GridLines.Both;
foreach (GridViewRow row in gridpurchase.Rows)
{
foreach (TableCell cell in row.Cells)
{
for (int i = cell.Controls.Count - 1; i >= 0; i--)
{
if (cell.Controls[i] is Image)
{
Image img = cell.Controls[i] as Image;
if (img.ImageUrl.Contains("plus.png") || img.ImageUrl.Contains("minus.png"))
{
cell.Controls.RemoveAt(i);
}
}
}
}
}
gridpurchase.Caption = "Purchase Orders Report";
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
System.IO.StringWriter strWriter = null;
System.Web.UI.HtmlTextWriter htmlWriter = null;
curContext.Response.Clear();
curContext.Response.Buffer = true;
curContext.Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode("PurchaseOrdersReport", System.Text.Encoding.UTF8) + ".xls");
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=UTF-8>");
strWriter = new System.IO.StringWriter();
htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
gridpurchase.RenderControl(htmlWriter);
curContext.Response.Write(strWriter.ToString());
curContext.Response.End();
}
Grid-view
<asp:GridView ID="gridpurchase" OnRowCommand="gridpurchase_RowCommand" OnRowDataBound="gridpurchase_RowDataBound" DataKeyNames="RequisitionID" GridLines="None" runat="server" CssClass="table text-nowrap" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Preview">
<ItemTemplate>
<asp:Image ID="imgPlus" runat="server" AlternateText="" ImageUrl="img/plus.png" Style="cursor: pointer" />
<asp:Panel ID="pnlproducts" runat="server" Style="display: none">
<asp:GridView ID="gvItems" CssClass="table table-bordered" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ItemName" HeaderText="Item Name" SortExpression="ItemName" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="SupplierName" HeaderText="Supplier Name" SortExpression="SupplierName" />
<asp:BoundField DataField="PurchaseOrderCode" HeaderText="Purchase Order Code" SortExpression="PurchaseOrderCode" />
</Columns>
</asp:GridView>
According to your markup, there is a gvItems GridView inside of each row of gridpurchase. You can retrieve every child GridView in your main loop:
foreach (GridViewRow row in gridpurchase.Rows)
{
GridView gvItems = row.FindControl("gvItems") as GridView;
gvItems.Columns[0].Visible = false;
foreach (TableCell cell in row.Cells)
{
...
}
}
Change your foreach loop like this
gridpurchase.HeaderRow.Cells[0].Visible = false;
foreach (GridViewRow row in gridpurchase.Rows)
{
row.Cells[0].Visible = false;
}
This will remove the first column from your asp:GridView

How to display and download word file from gridview?

I have developed a system to upload word file along with TITLE textbox but no idea how to display and download from gridview.
protected void UploadTender()
{
try
{
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/UploadedTenders/") + fileName);
HdnFieldUploadedTender.Value = fileName;
ResultLabel.ResultLabelAttributes("Tender Uploaded", ProjectUserControls.Enums.ResultLabel_Color.Red);
ResultPanel.Controls.Add(ResultLabel);
}
else
{
ResultLabel.ResultLabelAttributes("No file specified", ProjectUserControls.Enums.ResultLabel_Color.Red);
ResultPanel.Controls.Add(ResultLabel);
}
}
catch (Exception ex)
{
ResultLabel.ResultLabelAttributes(ex.Message, ProjectUserControls.Enums.ResultLabel_Color.Red);
ResultPanel.Controls.Add(ResultLabel);
}
finally { }
}
Gridview:
<asp:GridView runat="server" ID="grdviewUploadedTenders" OnRowCommand="grdviewUploadedTenders_RowCommand" DataKeyNames="pk_UploadedTenders_UploadedTenderID" AutoGenerateColumns="false" CssClass="table table-condensed table-bordered table-striped table-responsive">
<Columns>
<asp:BoundField DataField="pk_UploadedTenders_UploadedTenderID" HeaderText="Tender ID" />
<asp:BoundField DataField="UploadedTenderTitle" HeaderText="Tender Title" />
<asp:BoundField DataField="UploadedTenderRemarks" HeaderText="Remarks" />
<asp:BoundField DataField="UploadedTenderSystemEntryDateTime" HeaderText="Uploaded On" />
<asp:ButtonField CommandName="cmdEdit" ImageUrl="~/assets/global/images/shopping/edit.png" ButtonType="Image" ControlStyle-Width="25px" ControlStyle-Height="25px" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="~/assets/global/images/shopping/delete.png"
CommandName="cmdDelete" CommandArgument='<%# Container.DataItemIndex %>' OnClientClick="return confirm('Are you Sure ?');"
ControlStyle-Width="25px" ControlStyle-Height="20px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am storing file path in sql TABLE. It's been stored there but issue is getting and making it able to be downloaded.
Check this tutorial
Displaying the files from folder or directory in ASP.Net GridView
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Uploads/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
files.Add(new ListItem(Path.GetFileName(filePath), filePath));
}
GridView1.DataSource = files;
GridView1.DataBind();
}
}
Downloading the Uploaded File from ASP.Net GridView
protected void DownloadFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
Response.WriteFile(filePath);
Response.End();
}

Adding Dynamic Rows in Gridview and How to retain selected option from user control in Gridview

I have created user control named CRE.ascx,this control has 3 dropdownlist.
First dropdownlist bind data on pageload.Second and third based on SelectedIndexChanged.
<table cellspacing="0" cellspading="0" style="width:550px;height:30px;">
<tr>
<td style="width:30%;">
<asp:DropDownList ID="ddlCRE" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlCRE_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:30%;">
<asp:DropDownList ID="ddlDataPoints" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlDataPoints_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:30%;">
<asp:DropDownList ID="ddlErrorCode" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlErrorCode_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:10%;">
<asp:TextBox ID="tbxErrorScore" runat="server" style="height:17px;border:0px;font-family:'Segoe UI';font-size:13px;font-weight:500;color:white;background-color:#333333;
width:65px;" ReadOnly="true"> </asp:TextBox>
</td>
</tr>
</table>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Get Ticket Type Values
dbtickettype = helpdsktcktusrHandler.GetTicketType("DPT0001");
ddlCRE.DataSource = dbtickettype;
ddlCRE.DataValueField = "Type_ID";
ddlCRE.DataTextField = "Type_Name";
ddlCRE.DataBind();
ddlCRE.Items.Insert(0, new ListItem("Select Type", "SLCT0000"));
}
else
{
}
}
protected void ddlCRE_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedTypeID = ddlCRE.SelectedValue.ToString();
try
{
if (selectedTypeID == "SLCT0000")
{
ddlDataPoints.Items.Clear();
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketCategory = helpdsktcktusrHandler.GetTicketCategoryDetails(selectedTypeID);
//Binding Ticket Type values to Listbox
ddlDataPoints.DataSource = dbticketCategory;
ddlDataPoints.DataValueField = "Category_ID";
ddlDataPoints.DataTextField = "Category_Name";
ddlDataPoints.DataBind();
ddlDataPoints.Items.Insert(0, new ListItem("Select Category", "SLCT0000"));
//Clear Items
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
}
catch (Exception ex)
{
}
}
protected void ddlDataPoints_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedCatID = ddlDataPoints.SelectedValue.ToString();
try
{
if (selectedCatID == "SLCT0000")
{
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketSubCategory = helpdsktcktusrHandler.GetTicketSubCategoryDetails(selectedCatID);
//Binding Ticket Type values to Listbox
ddlErrorCode.DataSource = dbticketSubCategory;
ddlErrorCode.DataValueField = "Sub_Category_ID";
ddlErrorCode.DataTextField = "Sub_Category_Name";
ddlErrorCode.DataBind();
ddlErrorCode.Items.Insert(0, new ListItem("Select Subcategory", "SLCT0000"));
//Clear Items
tbxErrorScore.Text = string.Empty;
}
}
catch (Exception ex)
{
}
}
protected void ddlErrorCode_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedSubcatID = ddlErrorCode.SelectedValue.ToString();
try
{
if (selectedSubcatID == "SLCT0000")
{
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketIssues = helpdsktcktusrHandler.GetTicketIssueDetails(selectedSubcatID);
////Binding Ticket Type values to Listbox
//ddlstIssue.DataSource = dbticketIssues;
//ddlstIssue.DataValueField = "IssueID";
//ddlstIssue.DataTextField = "Issue_Name";
//ddlstIssue.DataBind();
tbxErrorScore.Text = dbticketIssues.Rows[0][1].ToString();
}
}
catch (Exception ex)
{
}
}
then register directive and an instance of the user control added to the page.
In this main page, i have added one Gridview, user control UC1 and two buttons
included in the ItemTemplate.
<%# Register src="~/CRE.ascx" TagName="InsertNewCRE" TagPrefix="uc1" %>
<asp:UpdatePanel ID="MainUpdatePanel" runat="server">
<ContentTemplate>
<div id="dvsubCRE" class="dvsubCRE" runat="server">
<!-----[[[ GRIDVIEW ADDING CRE ]]]----->
<div id="dvAddingErrorInfo" class="dvAddingErrorInfo">
<!-- LOAD CRE DROPDOWN INFO GRID -->
<asp:GridView ID="gvCREInfo" runat="server" CssClass="gvErrorInfo" AlternatingRowStyle-CssClass="" ShowFooter="false" ShowHeader="false"
EnableViewState="True" GridLines="None" EmptyDataText="No records found" AutoGenerateColumns="true" CaptionAlign="Left" CellPadding="0"
ShowHeaderWhenEmpty="True" OnRowCreated="gvCREInfo_RowCreated" OnRowCommand="gvCREInfo_RowCommand" >
<Columns>
<asp:BoundField DataField="RowNumber" />
<asp:TemplateField ItemStyle-Width="25%" ItemStyle-Height="20px">
<ItemTemplate>
<uc1:InsertNewCRE id="UC1InserCRE" runat="server" EnableViewState="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgbtnAddCRE" runat="server" Width="20px" Height="20px" value="" ImageUrl="~/Images/Tracker/add.png"
CommandName="ButtonAddCRERow" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<asp:ImageButton ID="imgbtnReoveCRE" runat="server" Width="20px" Height="20px" value="" Visible="false" ImageUrl="~/Images/Tracker/delete.png" CommandName="ButtonRemoveCRERow" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<!-- LOAD CRE DROPDOWN INFO GRID CLOSE -->
</div>
<!-----[[[ GRIDVIEW ADDING CRE CLOSE ]]]----->
</div>
</ContentTemplate>
</asp:UpdatePanel>
When main page loads, user control UC1 loaded in the gridview and pull out the data from CRE.ascx page.I have bind dummy data on page load to the gridview.Add new row along with user control mentioned in the RowCommand.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
gvCREInfo.DataSource = dt;
gvCREInfo.DataBind();
}
else
{
}
}
catch (Exception ex)
{
}
}
protected void gvCREInfo_RowCommand(object sender, GridViewCommandEventArgs e)
{
#region ADD NEW CRE ROW
if (e.CommandName == "ButtonAddCRERow")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvCREInfo.Rows[index];
int count = gvCREInfo.Rows.Count;
DataRow drCurrentRow = null;
UserControl UC1 = (UserControl)(row.Cells[0].FindControl("UC1InserCRE"));
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
for (int i = 0; i <= (count - 1); i++)
{
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows.Add(drCurrentRow);
}
gvCREInfo.DataSource = dtCurrentTable;
gvCREInfo.DataBind();
}
#endregion
}
When i run this code working fine and i changed the first dropdownlist
it will pull data and bind to the second, like wise third one also.But when i click the add button selected data lost in the first row and second row control added not with data.How to retain existing selected data and load user control along with data it should not loss data event post back.Please help me and sort out this.
![enter image description here][1]
http://i.stack.imgur.com/wdYZv.jpg

How to retain gridview data when postback?

I have fill data in grid view. And also i have written in code inside Row Data Bound for changing image URL to image.
Here is the code:
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
for (int i = 1; i < e.Row.Cells.Count; i++)
{
string cellValue = e.Row.Cells[i].Text.Trim();
if(cellValue.StartsWith("http:"))
{
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
img.ImageUrl = e.Row.Cells[i].Text.Trim();
HyperLink hb = new HyperLink();
hb.Controls.Add(img);
e.Row.Cells[i].Controls.Add(hb);
}
}
}
It is working fine. The page has another two drop down controls. If i select one drop down control, i made post back. At that time, the image inside i already wrote is changed to URL instead of Image.
Can you any one assist me to handle?
Thanks in advance.
Here is my code for the issues(i am not able to post entire code)
aspx code:
<html>
<body>
<form id="form1" runat="server">
<asp:DropDownList ID="DropDownList2" CssClass="borderradius" runat="server" Height="20px" Width="190px" AutoPostBack="True" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" Font-Size="11px">
</asp:DropDownList>
<asp:Button id="sidesbmt" runat="server" onclick="sidesbmt_click"/>
<asp:GridView ID="GridView1" runat="server" Width="100%" CssClass="mGrid" PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt" OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
BorderStyle="None" GridLines="Both">
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
</asp:GridView>
</body>
</html>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
}
protected void sidesbmt_Click(object sender, EventArgs e)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
for (int i = 1; i < e.Row.Cells.Count; i++)
{
string cellValue = e.Row.Cells[i].Text.Trim();
if(cellValue.StartsWith("http:"))
{
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
img.ImageUrl = e.Row.Cells[i].Text.Trim();
HyperLink hb = new HyperLink();
hb.Controls.Add(img);
e.Row.Cells[i].Controls.Add(hb);
}
}
}
This problem happens when you add controls dynamically and this control does not exist during the Page Init event. To restore the viewstate to the control after postback, the control has to be present in the control tree.
You can try changing your code a bit like this.
Conver the column which displays the image and url into template field
<asp:TemplateField>
<ItemTemplate>
<asp:Literal runat="server" ID="literalUrl" Text='<%#Eval("The fieldname")%>'></asp:Literal>
<asp:Image runat="server" ID="imageUrl" Visible="false" />
</ItemTemplate>
</asp:TemplateField>
Then in the rowdatabound event toggle the view of image and literal
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
for (int i = 1; i < e.Row.Cells.Count; i++)
{
string cellValue = e.Row.Cells[i].Text.Trim();
Literal literal = e.Row.Cells[i].FindControl("literalUrl") as Literal;
Image imageUrl = e.Row.Cells[i].FindControl("imageUrl") as Image;
if (literal != null && imageUrl != null)
{
if (literal.Text.StartsWith("http:"))
{
imageUrl.ImageUrl = literal.Text.Trim();
imageUrl.Viisible = true;
literal.Visible = false;
}
}
}
}

Getting row index of checked row

I am trying to do when the checkbox column in my gridview is marked, I get the row index. My gridview is in a repeater and when I setup the gridview, I put a DataKeyNames:
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<asp:Panel ID="pBody1" runat="server" CssClass="cpBody">
<asp:Label ID="lblBodyText1" runat="server" />
<!-- Grid view to show products based on each category -->
<asp:GridView ID="gvProduct" runat="server" AutoGenerateColumns="False" Width="998px" CellPadding="4" ForeColor="#333333" GridLines="None" ShowHeader="False" DataKeyNames="id">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="cbCheckRow" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="name" HeaderText="Name" ItemStyle-Width="600px" />
<asp:BoundField DataField="categoryName" HeaderText="Category" />
<asp:TemplateField HeaderText="Quantity" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:TextBox ID="tbQuantity" runat="server" Width="60" Text='<%# DataBinder.Eval(Container.DataItem, "inventoryQuantity") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
<asp:CollapsiblePanelExtender ID="cpe1" runat="server" TargetControlID="pBody1" CollapseControlID="pHeader1"
ExpandControlID="pHeader1" Collapsed="true" ImageControlID="imgArrows1"
CollapsedImage="~/Images/downarrow.jpg"
ExpandedImage="~/Images/uparrow.jpg" TextLabelID="lblHeaderText1" CollapsedText="Show"
ExpandedText="Hide" CollapsedSize="0"
ScrollContents="false">
</asp:CollapsiblePanelExtender>
</ItemTemplate>
</asp:Repeater>
<asp:LinkButton ID="lbnConfirm" runat="server" class="btn dark" style="float: right" OnClick="lbnConfirm_Click">Confirm</asp:LinkButton>
When my lbnConfirm is onclick, I perform this to get the row index and store them into a list:
protected void lbnConfirm_Click(object sender, EventArgs e)
{
GridView gv = (GridView)Repeater1.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
GridViewRow row = gv.SelectedRow;
string prodID = this.gv.DataKeys[row].Value.ToString();
List<DistributionStandardPackingUnitItems> distSPUList = new List<DistributionStandardPackingUnitItems>();
//Store the prodIDs into list
}
}
}
When I run the page, it told me object reference is not set to an instance at this line:
foreach (GridViewRow gr in gv.Rows)
Also the gv of this line:
string prodID = this.gv.DataKeys[row].Value.ToString();
told me that the gv does not contain a definition of missing reference. I thought I declared at the code above?
Edited Portion:
protected void lbnConfirm_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
string prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
tempList.Add(prodID);
for (int count = 0; count < tempList.Count; count++)
{
lblTest.Text = tempList[count] + ",";
}
}
}
}
}
}
Your approach is right, however you need to consider few more things:
You have to loop through the Repeater's items and find the Panel in
each item.
You have to find the GridView inside the Panel, not in the Repeater.
You have to find the DataKey Value by RowIndex, not by row.
EDIT : To test, add a Label outside the repeater:
<asp:Label ID="lblTest" runat="server" Text=""></asp:Label>
Also change the code to display Id in the label.
After rewriting lbnConfirm_Click() method, it should look like below:
protected void lbnConfirm_Click(object sender, EventArgs e)
{
List<string> tempList = new List<string>();
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
//GridViewRow row = gv.SelectedRow;
string prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
List<DistributionStandardPackingUnitItems> distSPUList = new List<DistributionStandardPackingUnitItems>();
//Store the prodIDs into list
tempList.Add(prodID);
}
}
}
}
lblTest.Text = string.Join(",", tempList);
}
The code above worked fine in my test! Only you have to be careful not to rebind the repeater at postback in Page_Load().
Hope it helps!
get the row index in the RowDataBound event :
protected void gvProduct_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.commandName=="select")
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = e.Row.RowIndex;
CheckBox chk = (CheckBox)e.Row.FindControl("cbCheckRow");
int code = Convert.ToInt32(this.gvProduct.DataKeys[e.Row.RowIndex].Value);
}
}
}

Categories

Resources