Hello i have my FileUpload in gridview.I upload image for every row and then click button called UPLOAD. So that it should get image path from every row and upload. Onclick listener for UPLOAD is UploadBtn_onClick.
Code for UploadBtn_onClick is
protected void UploadBtn_onClick(object sender, EventArgs e)
{
foreach (GridViewRow row in StudentGrid.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
try
{
UpdateEmailProperties objUpdateEmailId = new UpdateEmailProperties();
GridViewRow grdrow = (GridViewRow)((FileUpload)sender).NamingContainer;
FileUpload filename = (FileUpload)grdrow.Cells[5].FindControl("fileuploadimages");
objUpdateEmailId.StudId = int.Parse(row.Cells[6].Text);
objUpdateEmailId.Email = row.Cells[3].Text;
objUpdateEmailId.profilepath = "profilepics/" + filename;
int intStatus;
intStatus = Stud.UpdateStudentEmailId(objUpdateEmailId);
if (intStatus != 0)
{
lblWarning.Text = "Updated successfully";
}
else
{
lblWarning.Text = "Failed to Update";
}
}
catch (Exception ex)
{
//LogFile.CreateLog("User", "AddPlacement", ex.Message);
lblWarning.Text = "Error: " + ex.Message.ToString();
}
}
}
}
But i am getting error as
Unable to cast object of type 'System.Web.UI.WebControls.Button' to type 'System.Web.UI.WebControls.FileUpload'
.
I need to fetch name of file returned from loadfile
Related
I'm trying to upload a file using FileUpload, and it doesn't work. After I click the button, it reloads the page, but the image is not saved
Below code is from microsoft, but still not working
protected void uploadBtn_Click(object sender, EventArgs e)
{
Boolean fileOK = false;
String path = Server.MapPath("~/Sources/images/");
if (imageUpload.HasFile)
{
String fileExtension =
System.IO.Path.GetExtension(imageUpload.FileName).ToLower();
String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
}
if (fileOK)
{
try
{
imageUpload.PostedFile.SaveAs(path
+ imageUpload.FileName);
statusUploadLbl.Text = "File uploaded!";
}
catch (Exception ex)
{
statusUploadLbl.Text = "File could not be uploaded.";
}
}
else
{
statusUploadLbl.Text = "Cannot accept files of this type.";
}
}
Please help, thanks
I enter values in User Name and Password in two text boxes. When I click submit, I want the table adapter to check the database to see if those are really the values and allow the user to log in.
This is my code:
protected void Submit_Click(object sender, EventArgs e)
{
//assign text from the textboxes to variables
string userName = TextBox1.Text;
string passWord = TextBox2.Text;
lblError.Visible = true;
try
{
string passwordValue = Encrypt(passWord);
DataSet1.tblUserDataTable dataTable = proccessedProcess.Login(userName, passwordValue);
if (dataTable != null & dataTable.Count!=0)
{
DataSet1.tblUserRow dataRow = dataTable[0];
if (dataRow.nUserID.ToString() == "00000000-0000-0000-0000-000000000000")
{
lblError.Text = "";
}
else if(dataRow.nUserID.ToString() != "00000000-0000-0000-0000-000000000000")
{
Session["CurrentUserID"] = dataRow.nUserID.ToString();
Session["LoggedIn"] = "YES";
Session["LastLogin"] = DateTime.Now.ToString();
Session["UserName"] = dataRow.txtUserName;
HttpContext.Current.Response.Redirect("MainCustomer.aspx");
}
} else {
lblError.Text = "Incorrect UserID or Password";
}
}
catch (Exception E)
{
E.Message.ToString();
lblError.Text = E.Message;
}
}
in the catch section you have E.Message.ToString(); which has no effect. Either you have to set it to a label inorder to see if there is an exception happening or throw E
catch (Exception E)
{
// E.Message.ToString();
Throw;
}
How can I clear the HttpContext.Current.Request.Files list?
After the postback, this still contains the files.
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
this.SaveImages();
}
private Boolean SaveImages()
{
//loop through the files uploaded
HttpFileCollection _files = HttpContext.Current.Request.Files;
//Message to the user
StringBuilder _message = new StringBuilder("Files Uploaded:<br>");
try
{
for (Int32 _iFile = 0; _iFile < _files.Count; _iFile++)
{
if (!string.IsNullOrEmpty(_files[_iFile].FileName))
{
// Check to make sure the uploaded file is a jpg or gif
HttpPostedFile _postedFile = _files[_iFile];
string _fileName = Path.GetFileName(_postedFile.FileName);
string _fileExtension = Path.GetExtension(_fileName);
//Save File to the proper directory
_postedFile.SaveAs(HttpContext.Current.Request.MapPath("files/") + _fileName);
_message.Append(_fileName + "<BR>");
}
}
lblFiles.Text = _message.ToString();
return true;
}
catch (Exception Ex)
{
lblFiles.Text = Ex.Message;
//Refill images in control????
return false;
}
finally
{
//Clear HttpContext.Current.Request.Files!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
Hi I've an excel file which looks like this
id name age phne no and like this i have 35 columns.........
I'm using a webapplication for this in which I've a fileupload control,a button and two textboxes
fileuploadcontrol
button
textbox1
textbox2
Now when I upload the excel file on button click it should read complete file .........
and when I enter the required column in the textbox1 I get those column details only its like this
textbox1(c1,c4,c5,c30) I sholud get only those column details and in the other text box if I enter the location to be saved it should be saved in that location can any one help me with this I had finished till file uploading and reading.....all I need is how to evaluate those textboxes to get my required data
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (FileUpload1.PostedFile.ContentType == "application/xlsx")
{
path = Server.MapPath(".") + "\\inputfiles\\" + Guid.NewGuid() + FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(path);
Label1.Text = "File Uploaded Successfully...";
StreamReader reader = new StreamReader(FileUpload1.FileContent);
string text = reader.ReadToEnd();
}
else
Label1.Text = "Upload .xlsx File";
}
else
Label1.Text = "Upload file";
}
Check this:
Read and Display Data From an Excel File (.xsl or .xlsx) in ASP.NET
You can specify what columns you need to read on select query.
Regards
I got the answer myself .......ty for tryin to helpin me m postin my code if any needs in any case........
protected void btns_Click(object sender, EventArgs e)
{
string path = string.Empty;
location = Textbox2.Text;
if (fup1.HasFile)
{
try
{
path = Server.MapPath(".") + "\\uploadedfiles\\" + Guid.NewGuid() + fup1.FileName;
fup1.PostedFile.SaveAs(path);
lbl5.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
lbl5.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
excelfile(path);
}
}
void excelfile( string path)
{
string readfile = path;
// initialize the Excel Application class
Excel.Application app = new Excel.Application();
//Excel.Worksheet NwSheet;
Excel.Range ShtRange;
// create the workbook object by opening the excel file.
Excel.Workbook workBook = app.Workbooks.Open(readfile, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
// Get The Active Worksheet Using Sheet Name Or Active Sheet
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.ActiveSheet;
int index = 1;
System.Text.StringBuilder sb = new StringBuilder();
try
{
string[] values = Textbox1.Text.Split(new char[] { ',' });
int[] colindexs = new int[values.Length];
for (int i = 0; i < values.Length; i++)
{
colindexs[i] = Convert.ToInt16(values[i]);
}
while (((Excel.Range)workSheet.Cells[index, 1]).Value2 != null)
{
string str = "";
foreach (int col1 in colindexs)
{
str = str + Convert.ToString(((Excel.Range)workSheet.Cells[index, col1]).Value2) + ",";
}
str = str.Substring(0, str.Length - 1);
sb.Append(str);
sb.Append(Environment.NewLine);
index++;
}
Writetofile(sb.ToString());
ShtRange = workSheet.UsedRange;
}
catch (Exception ex)
{
app.Quit();
lbl5.Text=ex.Message;
}
}
void Writetofile(string content)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(location, true))
{
sw.Write(content);
sw.Flush();
}
}
}
I keep getting the following error and I don't know how to fix it. Any help would be great please
Exception Details:NullReferenceException was unhandled by users code: Object reference not set to an instance of an object.
protected void LbUpload_Click(object sender, EventArgs e)
{
ERROR: if(FileUpload.PostedFile.FileName == string.Empty)
{
LabelMsg.Visible = true;
return;
}
else
{
string[] FileExt = FileUpload.FileName.Split('.');
string FileEx = FileExt[FileExt.Length - 1];
if (FileEx.ToLower() == "csv")
{
FileUpload.SaveAs(Server.MapPath("CSVLoad//" + FileUpload.FileName));
}
else
{
LabelMsg.Visible = true;
return;
}
}
CSVReader reader = new CSVReader(FileUpload.PostedFile.InputStream);
string[] headers = reader.GetCSVLine();
DataTable dt = new DataTable();
foreach (string strHeader in headers)
dt.Columns.Add(strHeader);
string[] data;
while ((data = reader.GetCSVLine()) != null)
dt.Rows.Add(data);
GridView1.DataSource = dt;
GridView1.DataBind();
if (FileUpload.HasFile)
try
{
FileUpload.SaveAs(Server.MapPath("confirm//") +
FileUpload.FileName);
LabelGrid.Text = "File name: " +
FileUpload.PostedFile.FileName + "<br>" +
FileUpload.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload.PostedFile.ContentType + "<br><b>Uploaded Successfully";
}
catch (Exception ex)
{
LabelGrid.Text = "ERROR: " + ex.Message.ToString();
}
else
{
LabelGrid.Text = "You have not specified a file.";
}
File.Delete(Server.MapPath("confirm//" + FileUpload.FileName));
}
You are checking if the FileName is string.Empty, it sounds like you want to detect when the user clicked the button without selecting a file.
If that happens, the actual PostedFile property will be null (remember, the user didn't posted a file), you should use the FileUpload.HasFile property for that purpose:
protected void LbUpload_Click(object sender, EventArgs e)
{
if(FileUpload.HasFile)
{
LabelMsg.Visible = true;
return;
}
// ...
}
But I would recommend you also to add a RequiredFieldValidator.
More on validation:
Validating ASP.NET Server Controls
ASP.NET Validation in Depth
Are you sure that FileUpload and FileUpload.PostedFile is not null?
Either FileUpload or its PostedFile property must be null.