Not getting value in Viewstate in asp.net using C#? - c#

I am using a asyncfileupload control to upload a file there i am taking the path in a view state like this:
protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string name = System.IO.Path.GetFileName(e.FileName);
string dir = Server.MapPath("upload_eng/");
string path = Path.Combine(dir, name);
ViewState["path"] = path;
engcertfupld.SaveAs(path);
}
Now when i am trying to save that path in a buttonclick event i am not getting the value of viewstate:
protected void btnUpdate_Click(object sender, EventArgs e)
{
string filepath = ViewState["path"].ToString(); // GETTING NULL in filepath
}
In this filepath i am getting null actually i am getting error NULL REFERENCE EXCEPTION
What can I do now?

Put the Path value in the Session object instead of the ViewState, like this:
protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
....
string path = Path.Combine(dir, name);
Session["path"] = path;
}
Then in the Button Click:
protected void btnUpdate_Click(object sender, EventArgs e)
{
if (Session["path"] != null)
{
string filepath = (string) Session["path"];
}
}

I guess the upload process is not a "real" postback, so the ViewState will not be refreshed client side and won't contain the path upon click on btnUpdate_Click
What you should do is use the OnClientUploadComplete client-side event to retrieve the uploaded file name, and store it in a HiddenField that will be posted on the server on btnUpdate_Click.
Here is a complete example where the uploaded file name is used to display an uploaded image without post-back :
http://www.aspsnippets.com/Articles/Display-image-after-upload-without-page-refresh-or-postback-using-ASP.Net-AsyncFileUpload-Control.aspx

Related

Using textbox to gather user's destination path for exporting a CSV in C# Windows application?

I'm looking for an option that allows a user to input their destination folder (Usually copy/Paste) into a text box on a Windows Application, and append the file's name with a specific name. However, I'm stuck as to how to accomplish this.
//Exporting to CSV.
string folderPath = MessageBox.Show(textBox1_TextChanged);
File.WriteAllText(folderPath + "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv", csv);
So it can look like: C:/DIR_9132017.csv, or Documents/DIR_9132017.csv, depending on what the user inputs into the textbox. I have nothing in my textbox code section at the moment, if that also gives a clearer picture about the situation.
Any help will be greatly appreciated. Thank you!
You can either use FolderBrowserDialog or can just copy/paste the path and create the directory.
Using FolderBrowserDialog
Step1 : Create Browse button (so that the user can choose the directory)
Step2 : Create Export button (Place the code to write the file here)
private void browseButton_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
var folderPath = folderBrowserDialog1.SelectedPath;
textBox1.Text = folderPath;
}
}
private void exportToCsvButton_Click(object sender, EventArgs e)
{
var path = textBox1.Text;
var file = Directory.CreateDirectory(path);
var filename = "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv";
File.WriteAllText(Path.Combine(path, "test.csv"), "content");
}
Using Copy/Paste
Step1 : Create Export button (User copy pastes the path. System create the directory and writes the file)
private void exportToCsvButton_Click(object sender, EventArgs e)
{
var path = textBox1.Text;
var file = Directory.CreateDirectory(path);
var filename = "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv";
File.WriteAllText(Path.Combine(path, "test.csv"), "content");
}
You would use a FolderBrowserDialog for that. After adding it to your form, you can use it like this:
public void ChooseFolder()
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
folderPath = folderBrowserDialog1.SelectedPath;
}
}
Source: https://msdn.microsoft.com/en-us/library/aa984305(v=vs.71).aspx
You haven't specified whether it's WinForms or WPF, so I'm using WPF, but is should be the same in WinForms.
To select the folder, you could use FolderBrowseDialog as follows. This code should be placed inside a button or some other similar control's Click event.
if (folderBrowse.ShowDialog() == DialogResult.OK)
{
txtPath.Text = folderBrowse.SelectedPath;
}
txtPath being a TextBox your selected path displayed in. You can substitute it with a simple string variable if you don't want to use a TextBox.
And if you want the user to be able to drag-drop a folder into a TextBox, you can create a TextBox control, and in it's PreviewDragOver and Drop events, you can do the following.
private void txtPath_PreviewDragOver(object sender, DragEventArgs e)
{
e.Handled = true;
}
private void txtPath_Drop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
if (files != null && files.Length != 0)
txtPath.Text = files[0];
}
Using both above in combination user has the ability to either select the folder he/she wants by clicking a button, drag-and-drop a folder into the TextBox, or copy-paste the folder path into the TextBox.

how to maintain state for a table in asp.net

i am trying to upload a csv file data to DB.
the process is like :
i am extracting csv file data to DataTable.
validating DataTable fields .
if all good , loading them into DB on button click.
i am generating invTable at below validation method by passing saved csv file path on validate button click.
protected void ValidateData_Click(object sender, EventArgs e)
{
ValidateCsv();
}
private void ValidateCsv(string fileContent)
{
DataTable getCSVData;
getCSVData = GetData(fileContent);
invTable= Validate(getCSVData);
}
if am loading it on BulkUpload_Click, invTable is null.
ideally it should have data , as assinged in ValidateCsv method.
protected void BulkUpload_Click(object sender, EventArgs e)
{
MatchedRecords(invTable);
}
any idea how to maintain invTable data across postback?
Change your ValidateCsv to a function.
private DataTable ValidateCsv(string fileContent)
{
DataTable getCSVData;
getCSVData = GetData(fileContent);
invTable = Validate(getCSVData);
return invTable;
}
Then on your MatchedRecords, modify it to accept a DataTable parameter.
private void MatchedRecords(DataTable invTable) {
}
Then on your BulkUpload_Click event, reference to the ValidateCsv, now a function that returns the value of your DataTable to the MatchedRecords void.
protected void BulkUpload_Click(object sender, EventArgs e)
{
MatchedRecords(ValidateCsv('enter how you get the fileContent here...'));
}
Or
protected void BulkUpload_Click(object sender, EventArgs e)
{
DataTable valueTable = ValidateCsv('enter how you get the fileContent here...');
MatchedRecords(valueTable);
}

How can i use file upload control in dnn module programming?

I want to use file upload control in dnn module programming.
I know there is DnnFilePicker in dnn, but I want a simple code that each user can upload a file and after that can display, edit and delete it.
There is this code but is not complete.
<%# Register TagPrefix="dnn" Assembly="DotNetNuke.Web" Namespace="DotNetNuke.Web.UI.WebControls" %>
<dnn:DnnFilePicker runat="server" ShowFolders="false" ID="fpUserFiles" FileFilter="pdf,gif,jpg" />
In Page_Load event, set the folder:
// Limit filepath to user's folder
fpUserFiles.FilePath = FolderManager.Instance.GetUserFolder(User).FolderPath;
what should i do?
If you have some sort of Save event on your module view, you simply get the FileId of the file that was selected by the user to save it in the database:
protected void btnSubmit_Click(object sender, EventArgs e)
{
ModelData model = new ModelData {
FileId = fpUserFiles.FileID
};
// TODO: Save your model data
}
In your Page_Load event, you can also load model data (if user is editing an existing model) by setting the fileID on the File Picker. That will pre-select the file in the picker control.
fpUserFiles.FileID = model.FileId
To use the fileId in another module view, you can get it from your model data and get the attributes of the file like this example:
FileInfo fi = (FileInfo)FileManager.Instance.GetFile(model.FileId);
if (fi != null)
{
pic.ImageUrl = "/" + _currentPortal.HomeDirectory + "/" + fi.RelativePath;
}
With this code my problem is resolved.
each user can upload its files in its folder.
protected void Page_Load(object sender, EventArgs e)
{
username = UserController.GetCurrentUserInfo().Username.ToString();
}
protected void Button1_Click1(object sender, System.EventArgs e)
{
var folder = Server.MapPath("~/uploads/Company/" + username);
if (this.FileUpload1.HasFile)
{
Directory.CreateDirectory(folder);
this.FileUpload1.SaveAs(folder + "/" + this.FileUpload1.FileName);
}
}

File Upload path needed

Hi I am trying to save only the path of a file using fileupload . On clicking the button I want only the complete path that the user has selected into the file upload to be stored into the database. Just for testing purposes I am using labels in the code below but ultimately I will connect it to a data base.I only need to store the path selected by the user and not the file.
HTML
C# that I have been trying but not working
protected void Button1_Click(object sender, EventArgs e)
{
string g = FileUpload1.FileName;
string b =Convert.ToString(FileUpload1.PostedFile.InputStream);
//string filepath = Path.GetFullPath(FileUpload1.FileName.toString());
Label1.Text = g;
Label2.Text =b;
}
change your code as below:
protected void Button1_Click(object sender, EventArgs e)
{
string g = Server.MapPath(FileUpload1.FileName);
string b =Convert.ToString(FileUpload1.PostedFile.InputStream);
//string filepath = Path.GetFullPath(FileUpload1.FileName.toString());
Label1.Text = g;
Label2.Text =b;
}
You can't.
See also here: How can I get file.path in plupload?
If I get you correctly, this is some kind of intranet application?
If this needs to work within a closed domain, you might as well think about a desktop application instead.
You need a path for save file? Try this:
this.MapPath("~")
or
this.yourUploadFile.PostedFile.SaveAs(this.MapPath("~") + "YOUR FOLDER + NAME");

How can i use Function MenuItem in Function buttonCreate_Click

I am relatively new in C#. My question is: I have created a MenuStrip. I want to create with ButtonCreate_Click a Folder under the Directory path. So how can use the path in the Function buttonCreate? Is that possible?
private void buttonCreate_Click(object sender, EventArgs e)
{
string MyFileName = "Car.txt";
string newPath1 = Path.Combine(patheto, MyFileName);
//Create a folder in the active Directory
Directory.CreateDirectory(newPath1);
}
private void DirectoryPathToolStripMenuItem_Click(object sender, EventArgs e)
{
string patheto = #"C:\temp";
Process.Start(patheto);
}
Because you are declaring patheto in the menu items click event it is only a local variable to that scope. If you create a property for your form, then that property can be used within the forms scope. Something like this:
private string patheto = #"C:\temp";
private void buttonCreate_Click(object sender, EventArgs e)
{
string MyFileName = "Car.txt";
string newPath1 = Path.Combine(patheto, MyFileName);
// Create a folder in the active Directory
Directory.CreateDirectory(newPath1);
}
private void DirectoryPathToolStripMenuItem_Click(object sender, EventArgs e)
{
Process.Start(patheto);
}
This means that your variable patheto can be accessed anywhere within the form. What you have to remember is that wherever you declare your variables, they will only be accessible in that function/class or child functions/methods.

Categories