After upload show uploaded file in Asp.net - c#

I have this Asp.net code:
<asp:Panel ID="pnlCustomer" runat="server">
<p class=".SmallCaption">
<b>Edit report</b></p>
<table class="DataTable" id="Bug" cellspacing="0" cellpadding="2" width="100%" border="0">
<tr>
<td class="CellName" width="25%">
<asp:Label CssClass="CasualForm" id="lblUploadFile" runat="server">Save new file</asp:Label>
</td>
<td class="CellValue" width="25%">
<asp:FileUpload CssClass="formdata100" ID="fuUploadedFile" runat="server" />
</td>
<td class="CellName" width="50%" colspan="2"> </td>
</tr>
<tr>
<td class="CellName" width="25%">
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="BtnDeleteReport" style="float:left" OnClientClick="if(confirm('Do you really want to delete this report?')) {this.disabled = true;} else {return false;}" UseSubmitBehavior="false" />
</td>
<td class="CellName" width="25%"> </td>
<td class="CellName" width="47%">
<asp:Button ID="btnDownloadFile" runat="server" Text="Get Report" onclick="btnDownloadFile_Click" />
</td>
<td class="CellName" width="3%">
<asp:Button ID="btnSave" runat="server" Text="Edit" OnClientClick="if(checkFileUploadSize()) {return true;}" onclick="btnEdit_Click" CommandArgument="Edit" />
</td>
</tr>
</table>
</asp:Panel>
and this is backcode C#:
protected void btnEdit_Click(object sender, EventArgs e) {
Button btnThis = (Button) sender;
if (btnThis.Text == "Edit") {
Edit();
btnThis.Text = "Save";
} else if (btnThis.Text == "Save") {
Save();
//btnThis.Text = "Edit";
}
}
private void Save() {
ReadDataFromGUI();
// insert/update report in DB.
int _id = reportsHandler.Update(report);
Response.Redirect("~/ReportsEditor.aspx?id=" + _id);
}
private void ReadDataFromGUI() {
if (report == null)
report = new Support_Report();
report.id = report_id;
report.id_entity = int.Parse(ddlEntities.SelectedValue);
report.inactive = cbInactive.Checked;
report.name = txtName.Text.Trim();
report.description = txtDescription.Text.Trim();
report.report_condition = txtReportCondition.Text.Trim();
int _so;
isSortOrderInteger = int.TryParse(txtSortOrder.Text.Trim(), out _so);
if (isSortOrderInteger) {
report.sort_order = _so;
}
string StrFileName = Path.GetFileName(fuUploadedFile.FileName);
int IntFileSize = fuUploadedFile.PostedFile.ContentLength;
if (StrFileName != null && StrFileName != "") {
string path = Utility.Utility.GenerateTempFileName(StrFileName);
FileInfo fi = new FileInfo(path);
fuUploadedFile.PostedFile.SaveAs(path);
try {
var extension = Path.GetExtension(StrFileName).Replace(".", "");
report.report_type = extension;
if (extension == "mrt") {
var xml_doc = new XmlDocument();
xml_doc.Load(path);
report.report_file = xml_doc.OuterXml;
} else {
report.report_file = Convert.ToBase64String(File.ReadAllBytes(path));
}
} finally {
fi.Delete();
}
}
}
When I insert a file and want it to upload it looks like this: Before
But when I press the "save" button then that file is deleted on the page and refreshed the page. Still, that file is in the database but I can't see it on that page. Then it looks like this after saving: After Why is this happening? How to fix that it always shows me even after the update?

The file upload control can ONLY survie ONE post back. When you click on ANY button that causes a post-back, then the file upload REALLY starts. And once that is done, then your code has to grab + save that information about the file. When code behind is now done, the file-upload control is re-set, and the file can no longer be had, looked at, or used by the upload control.
And I not really sure of the logic of having a "edit" button. Why not just have a single save or submit button. I mean, some edit button not going to always be hit by the user - they will just start typing into the text boxes, and then hit save. But as noted, any button click (post-back) will cause the up-load to start, and then as noted, in that post back you have ONE chance to get that information.
With the introduciton fo a edit button, then a user might use the file upload to select a file, then say hit edit - that's going to trigger the post-back.
As a result, you need ONE save button to de-confuse the UI, but more important, on that save, you have to save that file, update your database, and in fact probably want to either hide the up-load control, or move on in your UI from the up-loader page to some other display of the information. So, you want user to enter information, select a file, and then hit ONE button to start the up-load, and then save the information entered. If you allow additonal files to be up-loaded, then want to save/setup some hidden field, or some such to keep track of that issue.

Related

How to upload a file and then insert into it database?

I can't figure out how to upload a file using the upload button and then insert into (along with other stuff) the database.
When I debug into btnRegister_Click, HasFile returns false.
Is there a way to persist HasFile across 2 different button onclicks?
Upload code:
<tr>
<td>Expense Receipt
</td>
<td class="blackDisplayName">
<asp:UpdatePanel ID="uplExpenseReceipt" runat="server" ViewStateMode="Enabled">
<ContentTemplate>
<asp:FileUpload ID="fuExpenseReceipt" runat="server" />
<asp:Button ID="btnUploadExpenseReceipt" runat="server" Text="Upload" OnClick="btnExpenseReceiptUpload_Click" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnUploadExpenseReceipt" />
</Triggers>
</asp:UpdatePanel>
<asp:Label ID="lblFileWarning" runat="server" Text="" Font-Bold="true" ForeColor="Red"></asp:Label>
</td>
</tr>
C# code behind:
protected void btnExpenseReceiptUpload_Click(object sender, EventArgs e)
{
if (!fuExpenseReceipt.HasFile)
{
lblFileWarning.Text = "Please browse your computer to load a pdf or jpg file";
return;
}
if (fuExpenseReceipt.PostedFile.ContentLength > 1000000)
{
lblFileWarning.Text = "file size must be < 1Mb";
return;
}
//if (!fuExpenseReceipt.PostedFile.ContentType.Equals("application/pdf") | !fuExpenseReceipt.PostedFile.ContentType.Equals("image/jpg"))
if (!fuExpenseReceipt.PostedFile.ContentType.Equals("application/pdf"))
{
lblFileWarning.Text = "Only pdf or jpg files are allowed to be uploaded";
return;
}
if (!Directory.Exists(#"C:\Ireland Resources\ExpenseReceipts"))
{
Directory.CreateDirectory(#"C:\Ireland Resources\ExpenseReceipts");
}
string FolderUpload = #"C:\Ireland Resources\ExpenseReceipts\";
string PostedFile = FolderUpload + User.Identity.Name + "-" + fuExpenseReceipt.PostedFile.FileName;
fuExpenseReceipt.SaveAs(PostedFile);
}
Register code:
<td class="blackDisplayName" align="right">
<asp:Button ID="btnRegister" runat="server" Text="Register" ValidationGroup="ExpenseRegistration"
OnClick="btnRegister_Click" CssClass="gray-gradient" SkinID="NONE"/>
</td>
C# code behind:
protected void btnRegister_Click(object sender, EventArgs e)
{
try
{
if (!fuExpenseReceipt.HasFile)
{
lblFileWarning.Text = "Please browse your computer to load a pdf or jpg file";
return;
}
byte[] expenseReceipt = null;
Stream fs = fuExpenseReceipt.PostedFile.InputStream;
byte[] bytFileData = new byte[fs.Length];
fs.Read(bytFileData, 0, Convert.ToInt32(fs.Length));
fs.Close();
expenseReceipt = bytFileData;
int tillID = Int32.Parse(hfTillID.Value);
double beforeVAT = double.Parse(txtBeforeVAT.Text);
double VAT = double.Parse(txtVAT.Text);
double totalAmount = double.Parse(txtExpenseTotal.Text);
lblExpenseMessage.Visible = true;
try
{
new TillEndOfDayDAL().SaveExpense(StationID, tillID, beforeVAT, VAT, totalAmount, txtExpenseDescription.Text
, expenseReceipt, Int32.Parse(ddlExpenseTypes.SelectedValue), Page.User.Identity.Name.ToUpper());
lblExpenseMessage.Text = "Sundry expense has been successfully registered.";
}
I resolved the issue by doing the following:
Removed the Upload button
Moved the PostBackTrigger to the end of the 'outer' UpdatePanel, which contains both the FileUpload Control and Register button.
Changed the PostBackTrigger ControlID to the Register button.

How do I validate multiple asp.net checkboxes in C#

I have spent a lot of time trying to get 4 checkboxes to validate in a web application. This web app has already been written, and uses checkboxes when it probably should use a checkboxlist. However, I believe it will be an inordinate amount of work to change all of the existing code, so being able to validate the existing 4 boxes would save me a total re-write.
I have been through stackoverflow looking for the answer for two days, and I found several answers that will help me if I have a single checkbox, but I can't get anything to work if I have multiple, and I just want to validate a single box.
Below is the checkbox info for the ascx form:
</asp:Panel>
<cc1:PopupControlExtender ID="PopupControlExtender1" PopupControlID="PanelTypeOwnership"
runat="server" TargetControlID="helpTypeOwnership" Position="Left">
</cc1:PopupControlExtender>
<strong> Type of Ownership:</strong></td>
<td class="style12">
</td>
<td class="style11">
</td>
<td>
<strong>
<div class="textBoxImg" id="helpTypeOwnership" runat="server" style="width: 24px;
float: right;">
</div>
</strong>
</td>
</tr>
<tr>
<td style="padding-left: 2px;" class="style2">
<asp:CheckBox ID="chbAgricultural" runat="server" CssClass="texLabel" Text=" Agricultural/Horticultural Society"
BorderStyle="None" Width="260px" />
</td>
<asp:CustomValidator runat="server" ID="validateCheckBoxes" EnableClientScript="true"
OnServerValidate="validateCheckBoxes_ServerValidate"
ClientValidationFunction="validateCheckBoxes_ServerValidate">Please select a type of ownership.</asp:CustomValidator>
<td valign="middle" align="left" class="style10">
<asp:CheckBox ID="chbEnducational" runat="server" CssClass="texLabel"
Text=" Educational" />
</td>
<td class="style12">
<asp:CheckBox ID="chbReligious" runat="server" CssClass="texLabel"
Text=" Religious" />
</td>
<td class="style11">
<asp:CheckBox ID="chbCharitable" runat="server" CssClass="texLabel"
Text=" Charitable" />
</td>
</tr> </table>
<div style="height: 39px;">
</div>
The code relating to the checkbox validation on the ascx.cs form is:
protected void validateCheckBoxes_ServerValidate(object source, ServerValidateEventArgs args)
{
if (!chbAgricultural.Checked && !chbEnducational.Checked && !chbReligious.Checked && !chbReligious.Checked)
args.IsValid = false;
else
args.IsValid = true;
}
The code for the submit button is:
protected void lbnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
MembershipUser mUser = Membership.GetUser(Page.User.Identity.Name);
if (mUser == null) return;
DateTime dateT = Convert.ToDateTime(TextBoxDateWrite.Text);
FairShareApplication451a.changeStatusToVoid(new Guid(mUser.ProviderUserKey.ToString()), GetParcelId());
FairShareApplication451a apl451a = FairShareApplication451a.CreateApplication451a(new Guid(mUser.ProviderUserKey.ToString()),
lblNumberApplication.Text, TextBoxCounty.TextBoxText, TextBoxTaxyear.TextBoxText, TextBoxContactName.TextBoxText, TextBoxContactPhone.TextBoxText, TextBoxStateIncorporated.TextBoxText, //
GetParcelId(), chbAgricultural.Checked, chbEnducational.Checked, chbReligious.Checked, chbCharitable.Checked, TextBoxOrganizationName.TextBoxText, TextBoxPropOwnerName.TextBoxText,//
TextBoxMailingAddress.TextBoxText,
TextBoxCity.TextBoxText, DDListControl2.SelectedValue, TextBoxZipCode.TextBoxText, //TextBoxState.TextBoxText
TextBoxPropertyDescriptions.TextBoxText,
TextBoxAuthorizedSignature.Text, TextBoxTitle.Text, dateT, "Not Reviewed",
PropertyAddress.TextBoxText, PropertyCity.TextBoxText, PropertyState.SelectedValue, PropertyZip.TextBoxText); // Convert.ToDateTime(TextBoxDateWrite.Text)
//save uploaded files
SaveUploadedFiles(apl451a.Id);
FileUploader1.ResetControl();
MailSend m_snd = new MailSend(Server, Request);
m_snd.SendMessage(apl451a.UserId, FairShare.MailSend.mailType.received);
Response.Redirect("~/securezone/CurrentApplications.aspx");
// ClearAll();
}
}
I am sure I am missing something. I am still able to submit forms without checking any boxes. Any help would be greatly appreciated.
Note: I am aware educational is spelled incorrectly. I inherited this site --I just haven't gotten around to changing it in all of the relevant places.
Another option is to create a property on the ASCX user control
public bool IsOneCheckboxChecked
{
get
{
return (chbAgricultural.Checked || chbEnducational.Checked || chbReligious.Checked || chbCharitable.Checked);
}
}
You can then remove this method: (and maybe avoid a postback in the process)
protected void validateCheckBoxes_ServerValidate
and when it is time to submit the form, check:
if (userControlInstance.IsOneCheckboxChecked)
{
// good to go.
}
To check if one or more of the checkboxes is checked, you just need
args.IsValid = (chbAgricultural.Checked || chbEnducational.Checked || chbReligious.Checked || chbCharitable.Checked)
(you had chbReligious in there twice).
And I'm fairly sure you need to tie the CustomValidator to a Control to check, unless there is something else in the page which isn't shown.
Why to give up with client side validation? In your CustomValidator you have:
OnServerValidate="validateCheckBoxes_ServerValidate"
and
ClientValidationFunction="validateCheckBoxes_ServerValidate"
You have ClientValidationFunction pointing to the same server function. Try something like the following:
ClientValidationFunction="validateCheckBoxes_CLIENTValidate"
Being the client function something like this:
<script type="text/jscript">
function validateCheckBoxes_CLIENTValidate(sender, e) {
e.IsValid = jQuery(".texLabel input:checkbox").is(':checked');
}
</script>
If you cannot resolve multiple checkbox values by css class name you can take a look to this link

c# postback dropdownlist always choose first value

I want to insert the selected item of drop down list into database but my drop down list keep returns the first option . auto post back is false .
codes here :
dropTask() = drop down list where I populate it from database.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dropTask();
}
}
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
String pathdirectory = (dropListActivity.SelectedItem.Text+"/");
String filepathImage = (pathdirectory + e.FileName);
EnsureDirectoriesExist(pathdirectory);
AjaxFileUpload1.SaveAs(Server.MapPath(filepathImage));
Session["filepathImage"] = filepathImage;
}
i had checked the value return from drop down list using label :
protected void btnDone_Click(object sender, EventArgs e)
{
if (Session["filepathImage"] != null)
{
string filepathImage = Session["filepathImage"] as string;
Label1.Text = filepathImage;
}
}
the label text show the first option of the drop down list value instead of the choice I have chosen . Please enlighten me on this .
ASPX:
<tr>
<td>
<h2>Upload your Story!</h2>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
</td>
</tr>
<tr>
<td colspan = "2"></td>
</tr>
<tr>
<td>
<b>Select Activity:</b>
</td>
<td>
<asp:DropDownList ID="dropListActivity" runat="server"
onselectedindexchanged="dropListActivity_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan = "2"></td>
</tr>
<tr>
<td>
<b>Story Title:</b>
</td>
<td>
<asp:TextBox ID="txtStoryTitle" runat="server"
ontextchanged="txtTitle_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
<b>Upload your files here:</b><br />
Multiple Images and 1 Audio file only.
</td>
<td class="style1">
<asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
onuploadcomplete="AjaxFileUpload1_UploadComplete"
/>
</td>
</tr>
<tr>
<td colspan = "2"></td>
</tr>
<tr>
<td>
<asp:Label ID="Label1" runat="server" ></asp:Label>
</td>
<td>
<asp:Button ID="btnDone" runat="server" Text="Done" onclick="btnDone_Click" />
</td>
</tr>
DropListActivity.SelectedItem.ToString should do the trick. There are a few other things you should keep in mind:
Make sure you are not populating the dropdownlist on a postback.
Selected value will only be available at the sever if the portion of
the page containing the dropdownlist control is posted back.i.e if
you are using an update panel your dropdownlist should be present
within that panel or if you are posting back the entire page then there wont be any problem at all provided you meet the first criteria.
Your event handler dropListActivity_SelectedIndexChanged will
always be fired when a page is posted back and the seleceted index
has changed. The event handler dropListActivity_SelectedIndexChanged will be called after the page_load subroutine is executed.
I assume you need something like:
private void SaveSelected()
{
ViewState["SelectedItem"] = dropListActivity.SelectedItem;
}
which you use on dropListActivity_SelectedIndexChanged and
private void LoadSelected()
{
if (ViewState["SelectedItem"] != null)
dropListActivity.SelectedItem = (ListItem)ViewState["SelectedItem"];
}
which you call after dropTask();
Please, refer to this post's answer
in dropListActivity_SelectedIndexChanged event do like
if(dropListActivity.Items.Count > 0)
{
ViewState["DropDownSelectedValue"] = dropListActivity.Item.SelectedValue;
}
and on Load or databind of drop down list event write
if(ViewState["DropDownSelectedValue"] != null && dropListActivity.Items.Count > 0)
{
dropListActivity.SelectedValue = ViewState["DropDownSelectedValue"].ToString();
}

Showing buttons if list view is empty

I have a list view which retrieves the data from sql data source. I am trying to make two buttons(Yes and No) and a label outside the list view visible only if the list view is not empty. The process is: a person enter the information into text boxes and click the button retrieve, if the entered data exists in the database, the list view shows certain information.
I have the following code:
protected void btnExistingRetrive_Click(object sender, EventArgs e)
{
if (lstExisting.Items.Count>0 )
{
lblIsITYou.Visible = true;
btnYes.Visible = true;
btnNo.Visible = true;
}
}
By default buttons and the label are not visible.
The problem is when i click on retrieve button it shows me the list view with the information but buttons a the label are still not visible. They became visible only when i double click the retrieve button. Please tell me what is my mistake?
Thank you
Use the ListView EmptyDataTemplate
<asp:ListView ID="ContactsListView"
DataSourceID="ContactsDataSource"
runat="server">
<LayoutTemplate>
<table runat="server" id="tblProducts">
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:Label ID="FirstNameLabel" runat="Server" Text='<%#Eval("FirstName") %>' />
</td>
<td>
<asp:Label ID="LastNameLabel" runat="Server" Text='<%#Eval("LastName") %>' />
</td>
</tr>
</ItemTemplate>
<EmptyDataTemplate>
<table class="emptyTable" cellpadding="5" cellspacing="5">
<tr>
<td>
<asp:Image ID="NoDataImage"
ImageUrl="~/Images/NoDataImage.jpg"
runat="server"/>
</td>
<td>
No records available.
</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:ListView>
do you bind listview before checking the items count?
Do this on postback instead of in the event.
In your Page_Load do something like this:
protected void Page_Load(object sender, EventArgs e)
{
bool visible = (lstExisting.Items.Count > 0); // assuming it's never null
lblIsITYou.Visible = visible;
btnYes.Visible = visible;
btnNo.Visible = visible;
}
If the above creates complications then do as I said first with postback:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
bool visible = (lstExisting.Items.Count > 0); // assuming it's never null
lblIsITYou.Visible = visible;
btnYes.Visible = visible;
btnNo.Visible = visible;
}
}

change asp:FileUpload to Visible="true" using a do while statement

I am trying to create a page that has a variable number of FileUpload fields, depending on the number selected from a drop down list by the user.
my .apsx code is as follows;
<tr>
<td>Number of photo's to upload</td>
<td><asp:DropDownList ID="DLPhotoCount" runat="server" OnSelectedIndexChanged="OnSelectedIndexChanged_PhotoCount" AutoPostBack="true">
<asp:ListItem Text="..."></asp:ListItem>
<asp:ListItem Text="1"></asp:ListItem>
<asp:ListItem Text="2"></asp:ListItem>
</asp:DropDownList></td>
</tr>
<tr>
<td>Picture 1:</td>
<td><asp:FileUpload runat="server" ID="Pic1" Visible="false"/></td>
</tr>
<tr>
<td>Picture 2:</td>
<td><asp:FileUpload runat="server" ID="Pic2" Visible="false"/></td>
</tr>
<tr>
<td><asp:Button runat="server" ID="BtnUploadFiles" text="Upload Files" OnClick="OnClick_BtnUploadFiles" Visible="false"/></td>
</tr>
and my C# is;
protected void OnSelectedIndexChanged_PhotoCount(object sender, EventArgs e)
{
string Pic = "Pic";
int PicNo = Convert.ToInt32(DLPhotoCount.SelectedItem.Text);
if (DLPhotoCount.SelectedItem.Text != "...")
{
string StPicNo = Pic + PicNo;
do
{
FileUpload StPicNo.Visible = true;
PicNo = PicNo + 1;
}
while (PicNo < Convert.ToInt32(DLPhotoCount.SelectedItem.Text + 1));
BtnUploadFiles.Visible = true;
}
else
{
Pic1.Visible = false;
Pic2.Visible = false;
BtnUploadFiles.Visible = false;
}
}
Open to suggestions on any alternatives if this isn't the best way to achieve the required functionality
Its a good practice to create file upload control dynamically based on the value selected from dropdownlist.
Sample examples to add fileupload controls using javascript are available under below links
http://www.aspsnippets.com/Articles/Uploading-Multiple-Files-using-JavaScript-Dynamic-FileUpload-Controls-in-ASP.Net.aspx
http://www.codeproject.com/Articles/24914/Multiple-Dynamic-File-Uploading
The advantage of this is you dont have to do a condition check in code behind file and no code change required if your business requires to add more file upload controls in future.

Categories

Resources