upload excel file using ASP.net and C# - c#

How to upload excel file using ASP.net and C#?

Would not be very easy it is ?
<!-- front end -->
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload Excel File"
onclick="btnUpload_Click" />
//backend
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (System.IO.Path.GetExtension(FileUpload1.FileName) == ".xls" || System.IO.Path.GetExtension(FileUpload1.FileName) == ".xlsx")
{
FileUpload1.SaveAs(Server.MapPath("~/upload/temp/Forecast.xls"));
}
}
}

In your aspx page you can use the following...make sure you have enctype="multipart/form-data" in your form tag it will allow the posting of files.
<form enctype="multipart/form-data">
<input type="file" id="excel-file" name="excel-file" />
<input type="submit" />
</form>
Getting the file from the form post...
protected void Page_Load(object sender, EventArgs e)
{
if(this.IsPostback)
{
var yourFile = this.Request.Files["excel-file"];
}
}

I use This
It works perfectly, without anything needed to be changed in the code.

Related

Get html value on Web User Control without runat="server"

I'm new to this world.
As you can see in the picture. This is my Default.aspx page where I have implemented a Web User Control(uc) called "adress.ascx".
My uc control is divided in 2 categories, first is Asp.net controls category and second is Html Controls category.
What is the scenario: I want to copy the value from Html Textbox to Asp:TextBox.
I have 2 options, either I can do with asp:Button or with html button(without runat="server")
Here is my code
<h1>ASP.NET Controls</h1>
<br />
<asp:Label runat="server" Text="Street"></asp:Label>
<asp:TextBox runat="server" ID="tbStreet" Text=""></asp:TextBox><br /><br />
<asp:Button ID="btnAsp" Text="Button ASP" runat="server"
OnClick="btnAsp_Click"
/>
<h2>-------------------------------</h2>
<h1>Html Controls</h1>
Street
<input type="text" name="Street" id="street"><br />
<br />
<button type="button" id="btnStreet">Button HTML!</button>
And here is my code "code behind" in c#
protected void btnAsp_Click(object sender, EventArgs e)
{
string value = Request.Form["street"];
}
When I run this code, the value I get is null
I hope you will find this helpful .
**Aspx Page**
<input type='button' id='btnAsp1' value='Shop Now' class='form-control'
value='Button:1' onclick='javascript:__doPostBack("btnAsp1");'
style='background-color:#3465aa; color:white' >
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
**Code Behind**
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["__EVENTTARGET"] != null &&
Request.Form["__EVENTTARGET"] == "btnAsp1")
{
btnAsp1_Click(null, null);
}
}
private void btnAsp1_Click(object sender, System.EventArgs e)
{
Response.Write("You Clicked on " +
Request.Form["__EVENTARGUMENT"].ToString());
}
Here is the solution.
Code for Defualt.aspx page.
<%# Register Src="~/WebUserControl.ascx" TagName="Add" TagPrefix="uc1"
%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<uc1:Add runat="server" ID="ucAdres" WidthFirstCollumn="175px" />
</body>
</html>
And here is the code for WebUserControl.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<form method="post" runat="server"
>
<h1>ASP.NET Controls</h1>
<br />
<asp:Label runat="server" Text="Street" ID="lable"></asp:Label>
<asp:TextBox runat="server" ID="tbStreet" Text="Text Asp.net text box"></asp:TextBox><br />
<br />
<asp:Button ID="btnAsp" runat="server" Text="Button Asp.net" OnClick="btnAsp_Click"/><br />
<input type="submit" id="btnHtml" value="Html Button" />
<h2>-------------------------------</h2>
<h1>Html Controls</h1>
Street
<input type="text" name="street" id="street" value="Text coming from HTML5"">
<br />
<br />
<button type="button" id="btnStreet">Button HTML!</button>
</form>
And here is the code of WebUserControl.ascx.cs
protected void btnAsp_Click(object sender, EventArgs e)
{
string value = Page.Request.Form["street"].ToString();
if (value != null)
{
tbStreet.Text = value;
} else
{
tbStreet.Text = "Nooooooooo";
}
}
I explain again, that you have a WebUserControl where you have 2 types of Controls(Asp.net and html). What you want to do is to copy from HTML to asp.net without runat="server".
I often has problem of Form so finally I found that I have 2 Forms, 1 on WebUserControl and 1 on Default.aspx.
Your screenshot shows a breakpoint on the following line:
string value = Request.Form["street"];
with value being null. However, from Using Breakpoints on MSDN (emphasis mine):
When you run this code in the debugger, execution stops whenever the breakpoint is hit, before the code on that line is executed
If you go to the next line, the line will run and populate value. To copy this into the ASP.net control, the following should be sufficient:
protected void btnAsp_Click(object sender, EventArgs e)
{
tbStreet.Text = Request.Form["street"];
}
I would caution that what you are trying to do probably has a better solution, so even if this solves your immediate problem you may find that other issues crop up further down the line.

request file not working in asp.net

i need to request file from fileupload that is created in html. my question is quite simple how do i do this?
i know there is this option : HttpPostedFile File = Request.Files["imagem"]; but when i try to do that my File returns NULL.
I dont know what am i doing wrong, but even this simple code example is not working and i dont know why .
<body>
<form id="form1" runat="server">
<div>
protected void Button1_Click(object sender, EventArgs e)
{
HttpPostedFile File = Request.Files["imagem"];
if ( File != null)
Response.Write("Sucesso");
}
</form>
</body>
and here is my aspx code example :
<input type="file" name="image" class="image-upload" /></div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
can any one explain what am i doing wrong ? thank you
Might just be a typo on here, but change your imagem to image
protected void Button1_Click(object sender, EventArgs e)
{
HttpPostedFile File = Request.Files["image"];
if ( File != null)
Response.Write("Sucesso");
}
In your aspx page you need to tell the form that it will be using files. I don't think its required but its good practice to also include an id in your input that matches your name.
<body>
<form id="form1" runat="server" method="post" enctype="multipart/form-data">
<input type="file" id="image" name="image" class="image-upload" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>
I'd recommend going with the asp.net file upload control:
<asp:FileUpload ID="pictureUpload" class="form-control input-sm input-spacing" runat="server" />
You can create these dynamically
FileUpload OneUpload = new FileUpload();
OneUpload.ID = "Upload" + MyIdNumber;
UploadsDiv.Controls.Add(OneUpload);
Then to access the file, you have:
pictureUpload.SaveAs(FilePathAndName);
You can also access different properties of the posted file...
pictureUpload.PostedFile.FileName
pictureUpload.PostedFile.ContentLength
pictureUpload.PostedFile.ContentType

Any idea how can I keep file between postback calls?

Here is ASP.NET code:
<div class="row1" style="padding: 3px">
<asp:Button Text="Select" ID="btnDescColumn" runat="server" OnClick="SetDescPoint" CausesValidation="False"/>
<input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" id="fileSelect" runat="server" class="hidden" />
<asp:Button ID="btnUpload" runat="server" Text="Load" OnClick="LoadFile" class="hidden" CausesValidation="False" />
<input type="button" id="triggerUpload" name="name" value="Select File" />
</div>
Here the view:
Here is JQuery code:
$('#triggerUpload').click(function () {
$('#<%=fileSelect.ClientID%>').trigger('click');
});
$('#<%=fileSelect.ClientID%>').change(function () {
$('#<%=btnUpload.ClientID%>').trigger('click');
});
When Select File button clicked dialog window opens and user select file.
After the file selected, this JQuery code fired:
$('#<%=fileSelect.ClientID%>').change(function () {
$('#<%=btnUpload.ClientID%>').trigger('click');
});
and the JQuery row above trigger this asp button control:
<asp:Button ID="btnUpload" runat="server" Text="Load" OnClick="LoadFile" class="hidden" CausesValidation="False" />
which is fire this code behind method:
protected void LoadFile(object sender, EventArgs e)
{
HttpPostedFile file = Request.Files[fileSelect.Name];
int fileSize = file.ContentLength;
byte[] fileByteArray = new byte[fileSize];
file.InputStream.Read(fileByteArray, 0, fileSize);
}
After the postBack Process button clicked and this code behind is fired:
protected void SetDescPoint(object sender, EventArgs e)
{
if(fileSelect.Value != string.Empty)
{
//make some process...
}
}
But the fileSelect control is empty.
As I understand input file not keep the file between postback calls.
I need to access the file in SetDescPoint code behind.
Any idea how can I keep file between postback calls?
When you uploading a file in asp.net .. you must do a full post-back .. which can only achieve by submitting the page (button click).. no jquery trick will work .. even if your postback button is under a updatepanel .. then also you will not get the physical file in server side

How to create onclick event in .cs file for html <Input> Tag?

How to create onclick event in .cs file for asp.net c# for html Tag ?
Example :-
< input type="button" id="btnBeforeOk" value="Ok" name="btnBeforeOk" style="width: 90%;" />
I want to create an event in .cs file how we can do this ?
OR
bool isEmail = Regex.IsMatch("nikunj#yahoo.com", #"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|asia|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel)\b)\Z", RegexOptions.IgnoreCase);
The above bool isEmail i want to in .aspx page ?
Very simple.
HTML:
<input type="button" id="btnBeforeOk" value="Ok" runat="server" name="btnBeforeOk" style="width: 90%;" />
Now go to HTML view of your page and double click on your button, it will generate event for you and button markup will be changed to below:
<input type="button" id="btnBeforeOk" value="Ok" runat="server" name="btnBeforeOk" style="width: 90%;" onserverclick="btnBeforeOk_ServerClick" />
and you can find below event in your code behind:
protected void btnBeforeOk_ServerClick(object sender, EventArgs e)
{
Response.Write("hello");
}
I hope it helps!
I think you should use :
<asp:Button ID="MyButton" runat="server" OnClick="YourEvent" />
And do whatever you want to do in the code behind :
protected void YourEvent(object sender, EventArgs e)
{
//work
}

ASP.net ParseControl if else statement

Hope someone help me with this.
Is this possible in asp.net?
protected void Page_Load(object sender, EventArgs e)
{
Control parsed = this.ParseControl(#"<% if (true){ %> <div> Show True
Content </div> <%} %>");
myPlaceholder.Controls.Add(parsed);
}
<asp:View id ="myPlaceholder" runat="server" />
EDIT:
and I also try this still doesn't work and others
<asp:PlaceHolder id ="myPlaceholder" runat="server" />
If this is possible how can I achieve this?.

Categories

Resources