Doc file does not download from UserControl in asp.net - c#

I have user control which contain a grid with candidate data. There a columns candidate name with template field link button. I have attached a rowcommand event on which I am downloading a word file. I have download doc file code which download my doc file from simple web page but this code is not working on user control. Can any one help me to out this problem. its giving the error response is not available
<asp:GridView ID="grdCandidate" runat="server" AutoGenerateColumns="false"
OnRowDataBound="grdCandidate_RowDataBound"
onrowcommand="grdCandidate_RowCommand">
<Columns>
<asp:BoundField DataField="Candidate ID" HeaderText="Candidate ID" />
<asp:TemplateField>
<HeaderTemplate>
Candidate Name
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="lnkResume" CommandName="Download" CommandArgument='<%#Eval("Candidate ID") %>'
runat="server" Text='<%#Eval("Candidate Name") %>' ToolTip='<%# "Download Resume - " + Eval("Candidate Name") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void grdCandidate_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "Download")
{
byte[] Attachment = null;
string Extension = string.Empty;
string Resume = "Resume";
ClsCandidateManager objCandidateManager = new ClsCandidateManager();
ClsSecureManager objSecureManager = new ClsSecureManager();
Attachment = objCandidateManager.GetCandidateAttachment(Convert.ToInt32(e.CommandArgument), out Extension);
if (Attachment != null && Attachment.Length > 0)
{
try
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
if (Extension == ".pdf")
{
Response.ContentType = "application/pdf";
}
else
{
Response.ContentType = "application/vsd-msword";
}
Response.AddHeader("content-disposition", "attachment;filename=" + Resume + Extension);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(Attachment);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
string str = ex.Message + ex.InnerException;
}
}
else
{
//ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'>alert('Resume is not Uploaded !');</script>");
}
}
}
catch (Exception ex)
{
string str = ex.Message + ex.InnerException;
}

Use the UpdatePanel as shown below,
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="View" OnClick="lnkDownload_Click"
CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="lnkDownload" />
</Triggers>
</asp:UpdatePanel>

Related

Why the image does not enter a variable?

aspx:
<asp:FileUpload runat="server" ID="PicUpload" CssClass="btn btn-sm xor"/>
aspx.cs:
PicUpload.SaveAs(Path.Combine("C:\\Users\\KeepKids\\KeepKids\\pics\\", PicUpload.FileName));
why PicUpload.FileName ="" ?
In one place I do the same action and I get the picture. and here I get ""
I am find from below link:
https://www.aspforums.net/Threads/136183/ASPNet-FileUpload-control-Issue-FileName-is-blank-always-blank/
Can you please try this:
**PicUpload.PostedFile.FileName**
Something like below:
protected void btnsubmit_Click(object sender, EventArgs e)
{
string filename = "";
if (uploadphoto.PostedFile != null)
{
filename = Path.GetFileName(uploadphoto.PostedFile.FileName);
if (filename != "")
{
uploadphoto.SaveAs(Server.MapPath("images/" + filename));
string path = "images/" + filename;
}
}
}
<asp:FileUpload ID="FileUploadControl" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload File"
onclick="UploadButton_Click" />
<br />
<asp:Label ID="lblMessage" Font-Bold="true" runat="server">
</asp:Label>
Below is the click event which picks up the filename from FileUploadControl
protected void UploadButton_Click(object sender, EventArgs e)
{
if(FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
lblMessage.Text = "Upload status: File uploaded!";
}
catch(Exception ex)
{
lblMessage.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}

Displays file icons in asp.net on GridView

I can't to display file icons according to file extensions in asp.net GridView.
The structure of GridView is nested
The tutorial is Displays file icons in asp.net
The error is :
Object reference not set to an instance of an object
In this line of code-behind :
if (!String.IsNullOrEmpty(lnkDownload.Text))
My code below.
Can you help me?
Thank you in advance for any help, really appreciated.
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvOrders" runat="server"
AutoGenerateColumns="false" CssClass="mGrid" Width="700"
HorizontalAlign="Center">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img id="fileImage" runat="server" src="" />
<asp:HiddenField ID="HiddenField1"
runat="server" Value='<%# Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Download" ItemStyle-
HorizontalAlign="Justify">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text='<%#
Eval("Name") %>' CommandArgument=
'<%# Eval("FullName") %>' runat="server"
OnClick="lnkDownload_Click"
OnClientClick="if (!confirm('Confirm ?'))
return false;"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string root = #FilePath;
string folder = GridView2.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvOrders = (GridView)e.Row.FindControl("gvOrders");
Label gvLabel = (Label)e.Row.FindControl("gvLabel");
Label gvFolder = (Label)e.Row.FindControl("gvFolder");
DirectoryInfo directory = new DirectoryInfo(root + "/" + folder);
FileInfo[] fileInfo = directory.GetFiles("*.*",
SearchOption.AllDirectories);
fCount = directory.GetFiles("*.*",
SearchOption.AllDirectories).Length;
gvLabel.Text = fCount.ToString();
long size = 0;
foreach (string file in Directory.GetFiles(root + "/" + folder,
"*.*", SearchOption.AllDirectories))
{
size += new FileInfo(file).Length;
}
gvFolder.Text = Math.Round((double)size / (double)(1024 * 1024),
2).ToString() + " MB";
LinkButton lnkDownload =
(LinkButton)e.Row.FindControl("lnkDownload");
HiddenField hf = (HiddenField)e.Row.FindControl("HiddenField1");
if (!String.IsNullOrEmpty(lnkDownload.Text))
{
HtmlImage image = (HtmlImage)e.Row.FindControl("fileImage");
image.Attributes.Add("src", GetIconForFile(hf.Value));
}
gvOrders.DataSource = fileInfo;
gvOrders.DataBind();
}
}
private string GetIconForFile(string fileText)
{
string extension = Path.GetExtension(fileText);
extension = extension.Trim('.').ToLower();
return "~/fileicons/" + extension + ".png";
}
You have a Nested GridView Structure and gvOrders is your inner GridView. So, you've to get LinkButton from inner GridView's row as like:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gvOrders = (GridView)e.Row.FindControl("gvOrders");
foreach (GridViewRow row in gvOrders.Rows)
{
LinkButton lnkDownload = (LinkButton)row.FindControl("lnkDownload");
HiddenField hf = (HiddenField)row.FindControl("HiddenField1");
if (!String.IsNullOrEmpty(lnkDownload.Text))
{
//... some code
}
}
}
}

Why Asp:GridView calls button click method in server side?

In my case i have asp:gridview with OnRowCommand calls server method but when i try to refresh my page manually then it also calls OnRowCommand method, i don't know where is the actual problem.
My Code:.aspx
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound" OnSelectedIndexChanged="CUG_OnSelectedIndexChanged" OnRowCommand="CugSubmit_onserverclick1" EnableViewState="true"BorderStyle="Solid" BorderColor="Gray" BorderWidth="1px" EditRowStyle-BorderStyle="Solid" EditRowStyle-BorderWidth="1px" EditRowStyle-BorderColor="Gray" HeaderStyle-BorderStyle="Solid" HeaderStyle-BorderWidth="1px" HeaderStyle-BorderColor="Gray" RowStyle-BorderStyle="Solid" RowStyle-BorderColor="Gray" RowStyle-BorderWidth="1px" EmptyDataRowStyle-BorderStyle="Solid" EmptyDataRowStyle-BorderColor="Black" EmptyDataRowStyle-BorderWidth="1px" SortedAscendingHeaderStyle-BorderStyle="Solid" SortedAscendingHeaderStyle-BorderColor="Black" SortedAscendingHeaderStyle-BorderWidth="1px">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Driver ID">
<ItemTemplate>
<asp:Label ID="lbl_Dri_Name" runat="server" Text='<%# Eval("VehicleNo") %>' Visible="false"></asp:Label>
<asp:TextBox ID="Dri_Name" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dedicated">
<ItemTemplate>
<asp:Label ID="lbl_Vehitype" runat="server" Text='<%# Eval("VehicleType") %>' Visible="false"></asp:Label>
<asp:CheckBox ID="Vehitype" runat="server" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="ProcessThis" Text="Submit" />
<asp:ButtonField CommandName="Select" ItemStyle-Width="30" Text="delete" HeaderText="Delete" />
<asp:TemplateField HeaderText="">
<ItemTemplate>
</ItemTemplate>
<FooterStyle HorizontalAlign="left" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add Row" onclick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns></asp:gridview>
My code:.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GetCUGList();
}
}
protected void CugSubmit_onserverclick1(object sender, GridViewCommandEventArgs e)
{
DL.CustomerProfile ObjInput = new CustomerProfile();
BL.CustomerInputBL ObjCustomerInputBL = new CustomerInputBL();
if (e.CommandName == "ProcessThis")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = Gridview1.Rows[index];
if (row.RowType == DataControlRowType.DataRow)
{
TextBox textBox = row.FindControl("Dri_Name") as TextBox;
CheckBox chk = row.FindControl("Vehitype") as CheckBox;
ObjInput.CustId = HttpContext.Current.Session["VidStr"].ToString();
ObjInput.CustName = HttpContext.Current.Session["FirstName"].ToString();
ObjInput.VehiNo = textBox.Text;
ObjInput.Update = "Insert";
if (chk.Checked == true)
{
ObjInput.VehiChk = 1;
}
else
{
ObjInput.VehiChk = 0;
}
string URL = "http://*****/CustomerServices.svc/CUGList/";
string OutStatus = ObjCustomerInputBL.GetConnection(ObjInput, URL);
var serializer = new JavaScriptSerializer();
//AllTypeDetails.Value = OutStatus;
DataSet data = JsonConvert.DeserializeObject<DataSet>(OutStatus);
string ds = data.Tables[0].Rows[0]["ErrorMessage"].ToString();
if (ds == "already exist")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number has already registered')", true);
GetCUGList();
}
else if (ds == "Not Use")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number is not in freightX')", true);
GetCUGList();
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Insert Request Sent to Admin')", true);
GetCUGList();
}
}
AddNewRowToGrid();
}
else if (e.CommandName == "ProcessThisUpdate")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = Gridview1.Rows[index];
if (row.RowType == DataControlRowType.DataRow)
{
TextBox textBox = row.FindControl("Dri_Name") as TextBox;
CheckBox chk = row.FindControl("Vehitype") as CheckBox;
ObjInput.CustId = HttpContext.Current.Session["VidStr"].ToString();
ObjInput.CustName = HttpContext.Current.Session["FirstName"].ToString();
ObjInput.Update = "Update";
ObjInput.VehiNo = textBox.Text;
if (chk.Checked == true)
{
ObjInput.VehiChk = 1;
}
else
{
ObjInput.VehiChk = 0;
}
string URL = "http://*******/CustomerServices.svc/CUGList/";
string OutStatus = ObjCustomerInputBL.GetConnection(ObjInput, URL);
var serializer = new JavaScriptSerializer();
//AllTypeDetails.Value = OutStatus;
DataSet data = JsonConvert.DeserializeObject<DataSet>(OutStatus);
string ds = data.Tables[0].Rows[0]["ErrorMessage"].ToString();
if (ds == "already exist")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number has already registered')", true);
GetCUGList();
}
else if (ds == "Not Use")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number is not in freightX')", true);
GetCUGList();
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Update Request Sent to Admin')", true);
GetCUGList();
}
}
}
}

File Downloading Error in ASP.NET - C# from Gridview

Kindly Look at the error screen. I just want to download file from template field in gridview I saving file in server directory and file path in db.
any with this fix or proper new solution
<asp:GridView ID="GridView1" runat="server"
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="File">
<ItemTemplate>
<%--<asp:LinkButton ID="lnkDownload" Text = "Download" CommandArgument = '<%# Eval("filepath") %>' runat="server" OnClick = "FilesDownload"></asp:LinkButton>
--%>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download"
Text='<%# Eval("Path") %>' CommandArgument='Eval("Path")'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download")
{ Response.Clear(); Response.ContentType = "application/octectstream";
Response.AppendHeader("content-dispositi­on", "filename=" + e.CommandArgument);
Response.TransmitFile(Server.MapPath("~/­File") + "//" + e.CommandArgument);
Response.End(); }
}
You need to follow the below steps:-
Add the TemplateField at the end as below.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text="Download" CommandArgument='<%# Eval("file") %>' runat="server" OnClick="DownloadFile"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
and in Code-behind do something like this:-
protected void DownloadFile(object sender, EventArgs e)
{
try
{
string filePath = (sender as LinkButton).CommandArgument;
System.Net.WebClient req = new System.Net.WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("Content-Disposition", "attachment;filename=\"" + Server.MapPath("~/YourFolder/" + filePath) + "\"");
byte[] data = req.DownloadData(Server.MapPath("~/YourFolder/" + filePath));
response.BinaryWrite(data);
response.End();
}
catch (Exception ex)
{
throw ex;
}
}
Reference link:- http://www.aspsnippets.com/Articles/Download-Files-from-GridView-using-LinkButton-Click-Event-in-ASPNet-using-C-and-VBNet.aspx
Hope that helps

Upload a file using AsyncFileUpload Control and store it

I am doing a project :
Front end - Visual Studio 2010
Technology : C#
Back end - Sql Server 2005
I am trying to upload a file using AsyncFileUpload Control and store it to "~/Image/" folder.
Script :
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server"
onuploadedcomplete="AsyncFileUpload1_UploadedComplete"/>
</ContentTemplate>
Code Behind :
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
if (AsyncFileUpload1.HasFile)
{
AsyncFileUpload1.SaveAs("~/Image/" + AsyncFileUpload1.FileName);
Label2.Text = "Recieved " + AsyncFileUpload1.FileName + " Content Type" + AsyncFileUpload1.PostedFile.ContentType;
}
}
But everytime its showing runtime error called :
The SaveAs method is configured to require a rooted path, and the path '~\Image\Filename.jpg' is not rooted.
May I know the error and its solution.
Thanks in advance,
Nikhil
I figured it out:
table width="100%" style="font: 8pt verdana">
<tr width="100%">
<td width="40%">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:HiddenField ID="HiddenField1" runat="server" />
</td>
<td width="40%"><asp:Label ID="lblPicStatus" runat="server"></asp:Label></td>
<td>
<asp:Button ID="Button2" runat="server" Text="Upload" BackColor="White"
BorderColor="#507CD1" BorderStyle="Solid" BorderWidth="1px"
onclick="Button2_Click"/></td>
</tr>
</table>
Code Behind,
protected void Button2_Click(object sender, EventArgs e)
{
try
{
con.Open();
if (FileUpload1.HasFile)
{
String fileExt = Path.GetExtension(FileUpload1.FileName);
if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".bmp" || fileExt == ".jpeg" || fileExt == ".png")
{
String path = "~/Image/" + FileUpload1.FileName;
cmd.CommandText = "update " + HttpContext.Current.User.Identity.Name + " set image = '" + path + "'";
cmd.Connection = con;
cmd.ExecuteNonQuery();
FileUpload1.SaveAs(Server.MapPath("~/Image/") + FileUpload1.FileName);
Response.Redirect(Request.RawUrl);
}
else
{
lblPicStatus.Text = "File to be uploaded is not an image";
}
con.Close();
}
}
catch (Exception a)
{
Response.Write(a.Message);
}
}
String path = "~/Image/" + FileUpload1.FileName;
Should be like this:
String path = Server.MapPath("~/Image/") + FileUpload1.FileName;

Categories