Exporting GridView to Excel - c#

I have a gridview with a button for exporting it's data to an Excel file. When the button is clicked, I receive the following error:
Control 'gvLogNotice' of type 'GridView' must be placed inside a form tag with runat=server.
However, the Grid is within a form tag, I tried it both using a MasterPage and using a page w/o a MasterPage and still get the same error.
This is my Gridview snippet w/ button:
<form id="form1" runat="server">
<div style="width:600px;">
<asp:GridView ID="gvLogNotice"
runat="server"
AutoGenerateColumns="false"
ShowFooter="false"
OnRowCancelingEdit="gvLogNotice_RowCancelingEdit"
OnRowEditing="gvLogNotice_RowEditing"
OnRowUpdating="gvLogNotice_RowUpdating"
onpageindexchanging="gvLogNotice_PageIndexChanging"
OnRowDataBound="gvLogNotice_RowDataBound"
EmptyDataText="There are no data records to display."
DataKeyNames="LogNoticeID"
AllowPaging="true"
PageSize="10"
AllowSorting="true"
OnSorting="gvLogNotice_sorting"
Width="700px">
<Columns>
<asp:TemplateField HeaderText="Log No." Visible="false">
<ItemTemplate>
<%#Eval("LogNoticeID")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLogNoticeID" runat="server" Enabled="false" Text=' <%#Eval("LogNoticeID") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Log Date" SortExpression="DateLogged">
<ItemTemplate>
<%#Eval("DateLogged")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDateLogged" runat="server" Text=' <%#Eval("DateLogged") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Log Description" HeaderStyle-Width="50px" sortexpression="LogNoticeDescript">
<ItemTemplate>
<%#Eval("LogNoticeDescript")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLogNoticeDescript" runat="server" Text=' <%#Eval("LogNoticeDescript") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Responsible Party" sortexpression="ResponsibleParty">
<ItemTemplate>
<%#Eval("ResponsibleParty")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtResponsibleParty" runat="server" Text=' <%#Eval("ResponsibleParty") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Planned Date" SortExpression="PlannedDate" >
<ItemTemplate>
<%#Eval("PlannedDate")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPlannedDate" runat="server" Text=' <%#Eval("PlannedDate") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Case Number" SortExpression="CaseNumber">
<ItemTemplate>
<%#Eval("CaseNumber")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCaseNumber" runat="server" Text=' <%#Eval("CaseNumber") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Log Status" SortExpression="LogStatus">
<ItemTemplate>
<%#Eval("LogStatus")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLogStatus" runat="server" Text=' <%#Eval("LogStatus") %>'></asp:TextBox>
<asp:RangeValidator ID="rgvtxtLogStatus" runat="server" ControlToValidate="txtLogStatus" MaximumValue="1" MinimumValue="0" Text="Only a Value of 1 or 0 is allowed." />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="images/edit.png" Width="25"
Height="25" CommandName="Edit" />
<%-- <asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/img/delete.png" CommandName="Delete"
OnClientClick="return confirm('Are you sure want to delete record?')" />--%>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Update">Update</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div><asp:Button runat="server" ID="btnExport" Text="Export to Excel"
onclick="btnExport_Click" /></div>
</form>
...This is the code behind the button:
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
gvLogNotice.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
...Second Approach: I also tried the following and I got an error that only one Form may exists:
protected void btnExport_Click(object sender, EventArgs e)
{
try
{
Response.ClearContent();
string attachment = "attachment; filename=MyExelFile.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter strWrite = new StringWriter();
HtmlTextWriter htmWrite = new HtmlTextWriter(strWrite);
HtmlForm htmfrm = new HtmlForm();
gvLogNotice.Parent.Controls.Add(htmfrm);
htmfrm.Attributes["runat"] = "server";
htmfrm.Controls.Add(gvLogNotice);
htmfrm.RenderControl(htmWrite);
Response.Write(strWrite.ToString());
Response.Flush();
Response.End();
}
catch (Exception ex) { }
}
Could I please get some help as to what I'm missing here? Thank you in Advance.

try this code on export button:
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
GridViewBind();
GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}

If you like to use 3rd party component then refer to this article.
http://www.codeproject.com/Articles/8411/C-class-library-for-exporting-data-to-CSV-Excel-fi

Try this
protected void Button2_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.RenderControl(hw);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}

private void ExportToExcel(DataTable dt)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Sheet1.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
GridView dgGrid = new GridView();
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
dgGrid.DataSource = dt;
dgGrid.DataBind();
dgGrid.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in dgGrid.HeaderRow.Cells)
{
cell.BackColor = dgGrid.HeaderStyle.BackColor;
}
foreach (GridViewRow row in dgGrid.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = dgGrid.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = dgGrid.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
dgGrid.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}

This happens when you don't have the VerifyRenderingInServerForm in your code.
Simply put this snippet after your export code and it will go away.
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}

Related

I am trying to export grid data into CSV but Audiofilename column data is not displaying

I am trying to export Grid data to csv file in asp.net i exported successfully but Audio File name column data is not displaying in downloaded file (it is button in TemplateField tag i need to print button text in csv file ) ,anything i forget to add ? How to fix this issue ? Thank you
.aspx code
<asp:GridView ID="GridView1" Font-Size="Medium" CssClass="mGrid" runat="server"
HeaderStyle-CssClass="header-center" PageSize="15"
AutoGenerateColumns="false" AllowPaging="True" AllowSorting="True"
OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<%--<asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-ForeColor="White" />--%>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#Eval("Id")%>' CommandArgument='<%#Eval("Id")%>' Visible="false">
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Vendor Name" />
<asp:BoundField DataField="AudFileSize" HeaderText="AudFileSize" />
<asp:BoundField DataField="AudFileDuration" HeaderText="AudFileDuration" />
<%-- <asp:TemplateField HeaderText="Audio FileName">
<ItemTemplate>
<asp:Button ID="btnAudioFileName"
Text='<%#System.IO.Path.GetFileNameWithoutExtension(Eval("AudioFileName").ToString())%>'
runat="server" CommandArgument='<%#Eval("AudioFileName")%>'
class="btn btn-link" CommandName="AudioFileName" />
<%-- <sup><asp:Label ID ="lblrepetedCount" Text='<%#Eval("Reject")%>' runat="server"
CommandArgument='<%#Eval("Reject")%>' CommandName="Reject"></asp:Label></sup>--%>
<%-- </ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Audio FileName">
<ItemTemplate>
<asp:Button ID="btnAudioFileName"
Text='<%#System.IO.Path.GetFileNameWithoutExtension(Eval("AudioFileName").ToString())%>'
runat="server" CommandArgument='<%#Eval("AudioFileName")%>'
class="btn btn-link" CommandName="AudioFileName" />
<%-- <sup><asp:Label ID ="lblrepetedCount" Text='<%#Eval("Reject")%>' runat="server"
CommandArgument='<%#Eval("Reject")%>' CommandName="Reject"></asp:Label></sup>--%>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="FirstName" HeaderText="Physician Name" />--%>
<%--<asp:BoundField DataField="PhysicianID" HeaderText="PhysicianID" />--%>
<asp:BoundField DataField="MrnNo" HeaderText="MrnNo" NullDisplayText=" " />
<asp:BoundField DataField="PatientName" HeaderText="PatientName" NullDisplayText=" "/>
<asp:BoundField DataField="PhysicianName" HeaderText="PhysicianName" />
<asp:BoundField DataField="Reject" HeaderText="Reject" Visible="false" />
<%--<asp:BoundField DataField="BucketName" HeaderText="Bucket Name" Visible="false" />--%>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lblBucketName" runat="server" Text='<%#Eval("BucketName")%>' CommandArgument='<%#Eval("BucketName")%>' Visible="false">
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs code here
protected void btnExportToCSV_Click(object sender, EventArgs e)
{
ExportGridToCSV();
}
private void ExportGridToCSV()
{
//To Export all pages
GridView1.AllowPaging = false;
FillData();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Transcribeworkdetails.csv");
Response.Charset = "";
Response.ContentType = "application/text";
GridView1.AllowPaging = false;
GridView1.DataBind();
string[] hiddenCols = { "", "Reject" };
StringBuilder columnbind = new StringBuilder();
for (int k = 0; k < GridView1.Columns.Count; k++)
{
bool isHidden = true;
foreach (string str in hiddenCols)
{
if (GridView1.Columns[k].HeaderText == str)
{
isHidden = false;
break;
}
}
if (isHidden)
columnbind.Append(GridView1.Columns[k].HeaderText + ',');
}
columnbind.Append("\r\n");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int k = 0; k < GridView1.Columns.Count; k++)
{
bool isHidden = true;
foreach (string str in hiddenCols)
{
if (GridView1.Columns[k].HeaderText == str)
{
isHidden = false;
break;
}
}
if (isHidden)
{
columnbind.Append(GridView1.Rows[i].Cells[k].Text + ',');
}
}
columnbind.Append("\r\n");
}
Response.Output.Write(columnbind.ToString());
Response.Flush();
Response.End();
}

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

Grid view locking button by user id

I have a gridview in my project where like twitter you can see other peoples post but i want to allow users to change there posts and because of that near every post i putted an edit button. Now my problem is i cant lock the button if the user didnt post that tweet. can you show me how i can check if the users id (a given variable) matches the tweet user id (hidden field) i thought on using the for each loop but i cant succeed using it.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
ShowHeader="False" onrowcommand="GridView1_RowCommand"
onrowediting="GridView1_RowEditing" OnRowCancelingEdit="GridView1_Cancel"
onrowupdating="GridView1_RowUpdating"
onrowdeleting="GridView1_RowDeleting" >
<Columns>
<asp:TemplateField HeaderText="UserName">
<ItemTemplate>
<asp:Label ID="lbl_Username" runat="server" Text='<%#Eval("UserName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tweet">
<ItemTemplate>
<asp:Label ID="lbl_Tweet" runat="server" Text='<%#Eval("TweetText") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Tbx_Tweet" runat="server" Text='<%#Eval("TweetText") %>' ></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Picture">
<ItemTemplate>
<asp:Image ID="Pic" runat="server" ImageUrl='<%#"~/UploadedImages/"+Eval("PicName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Like">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Like" CommandName="Like" CommandArgument='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ReTweet">
<ItemTemplate>
<asp:Button ID="Button2" runat="server" Text="ReTweet" CommandName="ReTweet" CommandArgument='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TweetID" Visible="true">
<ItemTemplate>
<asp:Label ID="lbl_TweetID" runat="server" Text='<%#Eval("TweetID") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserID" Visible="true">
<ItemTemplate>
<asp:Label ID="lbl_UserID" runat="server" Text='<%#Eval("UserID") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate >
<asp:LinkButton ID="Edit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="Delete" runat="server" Text="Delete" CommandName="Delete" />
<asp:LinkButton ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>
<asp:LinkButton ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class Tweets : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
bool f = true;
if (!IsPostBack)
{
foreach (GridViewRow row in GridView1.Rows)
{
Label l = row.FindControl("UserID") as Label;
//Response.End();
//if (int.Parse(l.Text.ToString()) != 1)
//{
// Response.End();
// row.Cells[7].Visible = false;
//}
}
BindGridview();
//foreach (GridViewRow row in GridView1.Rows)
//{
// Label l = row.FindControl("UserID") as Label;
// Response.Write(l.Text);
// //if (int.Parse(l.Text.ToString()) != 1)
// //{
// // Response.End();
// // row.Cells[7].Visible = false;
// //}
//}
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int userId = 1;
if (e.CommandName == "Like")
{
int index = Convert.ToInt32(e.CommandArgument);
Label l = GridView1.Rows[index].FindControl("lbl_TweetID") as Label;
TweetHelper.Like(int.Parse(l.Text), userId);
}
if (e.CommandName == "ReTweet")
{
int index = Convert.ToInt32(e.CommandArgument);
Label l = GridView1.Rows[index].FindControl("lbl_TweetID") as Label;
TweetHelper.ReTweet(int.Parse(l.Text), userId);
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
}
protected void GridView1_Cancel(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridview();
}
public void BindGridview()
{
int userId = 1;
ServiceReference1.WebServiceSoapClient objWs = new ServiceReference1.WebServiceSoapClient();
DataSet ds = objWs.SelectTweets(userId, false);
DataTable dt = ds.Tables[0];
GridView1.DataSource = dt;
foreach (GridViewRow row in GridView1.Rows)
{
Label l = row.FindControl("UserID") as Label;
//if (int.Parse(l.Text.ToString()) != 1)
//{
// Response.End();
// // row.Cells[7].Visible = false;
//}
Response.Write(l.Text);
}
//int i = 0,x=0,y=0;
//DataTable dt1 = new DataTable();
//foreach (DataRow row in dt.Rows)
//{
// foreach (object obj in row.ItemArray)
// {
// dt1.Rows.Add(dt.Rows[x][4]);
// x++;
// }
//}
//foreach (DataRow row in dt1.Rows)
//{
// foreach (object obj in row.ItemArray)
// {
// if (obj.ToString() == userId.ToString())
// {
// GridView1.Rows[i].FindControl("Buttons").Visible = true;
// }
// else
// {
// GridView1.Rows[i].FindControl("Buttons").Visible = false;
// }
// i++;
// }
//}
GridView1.DataBind();
foreach (GridViewRow row in GridView1.Rows)
{
Label l = row.FindControl("UserID") as Label;
//if (int.Parse(l.Text.ToString()) != 1)
//{
// Response.End();
// // row.Cells[7].Visible = false;
//}
Response.Write(l.Text);
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label TweetID = GridView1.Rows[e.RowIndex].FindControl("lbl_TweetID") as Label;
TextBox TweetText = GridView1.Rows[e.RowIndex].FindControl("Tbx_Tweet") as TextBox;
TweetHelper.Updatetweet(int.Parse(TweetID.Text), TweetText.Text);
GridView1.EditIndex = -1;
BindGridview();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
}
You have more options to do it.
Create RowDataBound event handler and set up edit button Visibile/Enable property:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label userIdLbl = (Label)e.Row.FindControl("lbl_UserID");
LinkButton editBt = (LinkButton)e.Row.FindControl("Edit");
editBt.Visible = currentUserId == Convert.ToInt32(userIdLbl.Text);
}
}
Create a method in your code behind to check if the userId is currentUserId and add the attribute Visible/Enable to your edit button in gridview template:
Visible='<%# IsCurentUserId((int)Eval("UserID")) %>

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();
}

To download selected filename in grid view

In the below code i get attachment file names in a session i have bind the documnetid,attachmentname and download.but when i select 1st attachmnet filename it is downloading second attchmt filename.My aim is to download what i select in grid view.
eg
document id attchfilename download
1 xxx view
2 yyy view
Markup
<asp:GridView ID="Attchdwnld" runat="server"
AllowPaging="true"
AllowSorting="true"
AlternatingRowStyle-CssClass="alt"
AutoGenerateColumns="false"
CellPadding="4"
CssClass="mGrid"
ForeColor="#333333"
PageSize="10"
PageSize-Mode="NumericPages"
PagerStyle-CssClass="pgr"
PagerStyle-Visible="true"
ShowFooter="false"
Width="100%"
OnRowCommand="Attchdwnld_RowCommand" >
<Columns>
<asp:TemplateField HeaderText="DocumentID" ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="DocumentID" runat="server" Text='<%#Eval("DocumentID") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AttachmentFileName" ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="AttachmentFileName" runat="server" Text='<%#Eval("AttachmentFileName") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DownLoad" ItemStyle-Width="150px">
<ItemTemplate>
<asp:LinkButton ID="lnlbtnAttch" runat="server" Text="View" CommandName="Edit">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle Font-Bold="True" ForeColor="White" />
</asp:GridView>
Code-behind
protected void Attchdwnld_RowCommand(object sender, GridViewCommandEventArgs e)
{
var SearchDoc = (SearchDoc)Session["Documentname"];
lblMessage.Text = SearchDoc.AttachmentFileName;
string fileurl = "C:\\Search\\" + stName + "\\" + strtFolder + "\\" + lblMessage.Text;
string filename = fileurl;
if (filename != "")
{
string path = filename;
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}
}
I don't see why you should store Session["Documentname"] in your code at all. So I am omitting that part.
Try this code
protected void Attchdwnld_RowCommand(object sender, GridViewCommandEventArgs e)
{
// gets the clicked row of your GridView
var row = ((LinkButton)e.CommandSource).NamingContainer as GridViewRow;
//gets the filename in the cliked row
var attachmentNameLabel = row.FindControl("AttachmentFileName") as Label;
//store it to lblMessage's Text
lblMessage.Text = attachmentNameLabel.Text;
var filePath = String.Format("C:\\Search\\{0}\\{1}\\{2}",
stName, strtFolder, lblMessage.Text);
var file = new System.IO.FileInfo(filePath);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}

Categories

Resources