Object reference not set to an instance of an object - asp.net

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.

Related

Thread disrupting execution of ASP.net main application

I have an ASP.net web app that spawns a process (in a thread). This thread calls a '.dll' to connect to another 'subsystem'.
Problem is, when there are errors connecting to the 'subsystem', it affects my main application (main UI) and I get a 'connection refused message'. I have already put in 'try-catch' error handling routines in my thread. FYI, I would like to treat the thread as a 'Fire and forget' thread.
The thread is spawned when btnSubmit is clicked.
Please refer to trimmed-down extract of code.
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
txt_hide.Value = sStatus;
if (sStatus == "")
{
//create thread for posting
id = Guid.NewGuid();
Thread th = new Thread(() => postXMLClass.PostXML(sSeqNo));
th.Start();
sStatus = "Transaction generated..please check posting status..";
lblMessage.Text = "Transaction Generated...";
}
else
{
FormView1.DataBind(); //refresh the form
clib.Show2("Error generating transaction : " + sStatus, sender);
lblMessage.Text = "Error generating transaction : " + sStatus;
}
}
catch (SqlException ex)
{
lblMessage.Text = "Error generating transaction ...: " + ex.Message;
}
catch (Exception ex)
{
//sqc.Transaction.Rollback();
lblMessage.Text = "Error encountered...: " + ex.Message;
throw;
}
finally
{
if (dbc != null) dbc.Dispose();
if (clib != null) clib.Dispose();
}
}
public static void PostXML(string inlinkcode)
{
string sToken = "", sXMLOut = "";
Xml.Router.XMLRouter cX = new Xml.Router.XMLRouter();
try
{
cX.set_Options("com.xml.router.nameServer", appSetArray[0]);
cX.set_Options("com.xml.router.nameServerPort", appSetArray[2]);
cX.set_Options("com.xml.router.logicalServerName", appSetArray[1]);
{
sLinkcode = inlinkcode;
if (sLinkcode != null && sLinkcode != "")
{
strxml = "<?xml version=\"1.0\" encoding='UTF-8' ?>";
strxml += "<TableLinkRequest version=\"1.0\"><DocumentLinkStart><Request><StartParams>";
strxml += "<CmpCode>X</CmpCode><DocCode></DocCode></TableLinkRequest>";
sXMLOut = cX.Send(sToken, strxml);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception {0}", ex.Message);
}
finally
{
if (cX != null) cX.Logoff(sToken);
}
}

Null reference error when calling a method

I have a method called NewBatch_GetAndSetBatchID.
When I call this methode in the Page_Load methode it works perfectly.
But when I call this methode from a button (on the same page), I get:
Null reference exeption Object reference not set to an instance of an object.
It throws an error at:
BatchNoTextBox.Text = (batchID += 1).ToString();
When I debug, I can see that my batchID is filled with a value.
This is my code:
public void NewBatch_GetAndSetBatchID()
{
FormView1.ChangeMode(FormViewMode.Insert);
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand sqlCommando = new SqlCommand("SELECT MAX(BatchNo) FROM BM_BrewBatchHeader", conn);
try
{
conn.Open();
batchID = Convert.ToInt32(sqlCommando.ExecuteScalar());
}
catch (Exception)
{
}
finally
{
conn.Close();
}
}
}
catch (SqlException error)
{
}
try
{
TextBox BatchNoTextBox = (TextBox)FormView1.FindControl("BatchNoTextBox");
BatchNoTextBox.Text = (batchID += 1).ToString();
}
catch (Exception)
{
throw;
}
}
What can be the problem here?
I found the solution on another forum:
I have to use the PreRender trigger from the FormView. With the code below it works fine. When I now set the Formview to insert or edit mode the code executes perfectly.
protected void FormView1_PreRender(object sender, EventArgs e)
{
// if the mode is Edit or Insert
if (this.FormView1.CurrentMode == FormViewMode.Edit || this.FormView1.CurrentMode == FormViewMode.Insert)
{
TextBox BatchNoTextBox = (TextBox)FormView1.FindControl("BatchNoTextBox");
BatchNoTextBox.Text = (batchID += 1).ToString();
}
}

How to get pathname of image from FileUpload in grid view

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

Adding a new item in database through combobox

I am having a database and I use it through Entity Framework, I need to update the data by editing the other items in text boxes and grid, that is working fine and below is the code:
In aspx.cs
protected void SaveBtn_Click(object sender, EventArgs e)
{
obj.Address = AppAddress.Text;
obj.City = AppCity.Text;
obj.Email = AppEmail.Text;
obj.Notes = AppComments.Text;
obj.Postal = AppPostal.Text;
obj.AppraiserAppraiserCompanyId = ApprCompCmbx.SelectedIndex;
obj.ProvinceState = Province.SelectedIndex;
apprblobj.GetUpdate(obj);
Response.Write("<script>alert('You have successfully updated the Data');</script>");
}
call in the BL:
public void GetUpdate(Appraiser appObj)
{
obj.UpdateData(appObj);
}
and in the DAL
public void UpdateData(Appraiser apprObj)
{
try
{
var Appsave = context.Appraisers.FirstOrDefault(App => App.AppraiserId == apprObj.AppraiserId);
if (Appsave != null)
{
Appsave.AppraiserName = apprObj.AppraiserName;
Appsave.AppraiserAppraiserCompanyId = apprObj.AppraiserAppraiserCompanyId;
Appsave.Address = apprObj.Address;
Appsave.City = apprObj.City;
Appsave.ProvinceState = apprObj.ProvinceState;
Appsave.Email = apprObj.Email;
Appsave.Postal = apprObj.Postal;
Appsave.Notes = apprObj.Notes;
context.SaveChanges();
}
}
catch (Exception ex)
{
log.Debug("Appraiser : UpdateData: " + ex.Message + " Trace : " + ex.StackTrace);
}
}
Now I wanto to add a new item through the same combobox and on the button click functionality as it is doing all the work like add, update and delete.
Kindly provide me the hint: This I know that addobject(__) will ve used in place of savechanges etc.

Table adapter with visual studio Final Code

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;
}

Resources