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();
}
}
Related
I use Dapper to select data form Mssql, It result display "null"
(use stored procedureć List to get data, and "myDictionary[0].Account" and myDictionary[0].Password to get detail information) ,
but MS SQL database have data.
How can I fix code ? thanks.
public void Do_Click(object sender, EventArgs e)
{
string strAccount = Request.Form["userAccount"];
string strPassword = Request.Form["userPwd"];
using (var conn = new SqlConnection(strConn))
{
try
{
conn.Open();
List<LoginModel> myDictionary =
conn.Query<LoginModel>(#"uspSelectLoginChk",
new { LoginAcc = strAccount, LoginPsd = strPassword }, commandType: CommandType.StoredProcedure).ToList();
string strAccountChk = myDictionary[0].Account;
string strPASChk = myDictionary[0].Password;
conn.Close();
if (strAccountChk != null && strAccountChk != null)
{
Response.Redirect("test.aspx");
}
else
{
}
}
catch (Exception ex)
{
response.write( ex.ToString());
}
}
}
Try this one,
// Modified your code
public void Do_Click(object sender, EventArgs e)
{
string strAccount = Request.Form["userAccount"];
string strPassword = Request.Form["userPwd"];
var _para = new DynamicParameters();
_para.Add("#LoginAcc", strAccount);
_para.Add("#LoginPsd", strPassword);
var _list = _con.Query<LoginModel>("uspSelectLoginChk", _para, commandType: CommandType.StoredProcedure); // _con is SqlConnection _con = new SqlConnection("your connection string")
if(_list != null) {
Response.Redirect("test.aspx");
}
}
you need to check:
execute sp in sql with parameter which can view in debug the code.
example:
exec uspSelectLoginChk 'LoginAccValue', 'LoginPsdValue'
if a any data in sql execute,your code is error,if no data, you can insert data before with a data debug result.
Thanks
How do I implement my checkbox to stay check as it is even if user redirects to another page? Example, in my code behind when I check the checkbox the system updates the database and it says "Validated" , but when I press GoBackTeacher_Click event it will redirect to another page. In that another page there is a button function there that will redirect to this current page where my code behind function is implemented and checkbox is checked.
Aspx Code:
<div class="container" style="text-align: center; margin: 0 auto;">
<br />
<h1>Validation of Subjects</h1>
<br />
<asp:GridView runat="server" CssClass="table table-hover table-bordered" ID="ValidateSubject" Style="text-align: center"></asp:GridView>
</div>
<div style="float: right; padding-right: 75px;">
<button type="button" runat="server" class="btn btn-success" onserverclick="GoBackTeacher_Click">Go Back</button>
</div>
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace SoftwareAnalysisAndDesign.SAD
{
public partial class ValidateSubjectTeacher : System.Web.UI.Page
{
CheckBox check = new CheckBox();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["ValidateSubject"] == null)
{
Response.Redirect("TeacherPage.aspx", true);
}
if (!IsPostBack)
{
ValidateSubject.DataSource = Session["ValidateSubject"];
ValidateSubject.DataBind();
}
//Add a checkbox in the last row of GridView Progmatically
foreach (GridViewRow row in ValidateSubject.Rows)
{
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox; //position Check column on last row in gridview
check.Enabled = true;
check.CheckedChanged += ValidateSubject_Click; //Bind the event on the button
check.AutoPostBack = true; //Set the AutoPostBack property to true
}
}
protected void ValidateSubject_Click(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow grvRow = (GridViewRow)chk.NamingContainer;//This will give row
string validated = "Validated";
string notyetvalidated = "Not yet validated";
string studid = grvRow.Cells[0].Text;
string coursenum = grvRow.Cells[1].Text;
if (chk.Checked)
{
grvRow.Cells[10].Text = validated;
//Open Connection
using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SAD;Integrated Security=True"))
{
//Open Connection to database
try
{
conn.Open();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
using (SqlCommand cmd = new SqlCommand("Update AssessmentForm set Status = #Validated where StudentID = #studentID and CourseNo = #Coursenumber" ,conn))
{
cmd.Parameters.AddWithValue("#Validated", validated);
cmd.Parameters.AddWithValue("#studentID", studid);
cmd.Parameters.AddWithValue("#Coursenumber", coursenum);
cmd.ExecuteNonQuery();
}
//Close Connection to database
try
{
conn.Close();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
}
}
else
{
grvRow.Cells[10].Text = notyetvalidated;
//Open Connection
using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SAD;Integrated Security=True"))
{
//Open Connection to database
try
{
conn.Open();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
//query database to update the Status
using (SqlCommand cmd = new SqlCommand("Update AssessmentForm set Status = #Validated where StudentID = #studentID and CourseNo = #Coursenumber", conn))
{
cmd.Parameters.AddWithValue("#Validated", notyetvalidated);
cmd.Parameters.AddWithValue("#studentID", studid);
cmd.Parameters.AddWithValue("#Coursenumber", coursenum);
cmd.ExecuteNonQuery();
}
//Close Connection to database
try
{
conn.Close();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
}
}
}
protected void GoBackTeacher_Click(object sender, EventArgs e)
{
Response.Redirect("TeacherPage.aspx");
}
}
}
To further understand my question, here is an image to further explain it.
This is when I check the checkbox without pressing the go back button
And this where I go pressed the go back button and in the another page there is a proceed button to redirect to this current page where my gridview is located.
There the checkbox is unchecked, and the status says it is validated. How do I implement my code that checkbox stay checked?
Is it something to do with postback? Please help.
UPDATE
I've tried this, it will stay checked my redirecting to this page, but when checkbox is clicked the status will not change from "Validated" to "Not yet validated" it will not change on postback when clicked.
foreach (GridViewRow row in ValidateSubject.Rows)
{
bool isChecked = default(bool);
if (row.Cells[row.Cells.Count - 2].Text.Equals("Validated")) // Here please assign the position of **Status** column.
{
isChecked = true;
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox; //position Check column on last row in gridview
check.Enabled = true;
check.CheckedChanged += ValidateSubject_Click; //Bind the event on the button
check.AutoPostBack = true; //Set the AutoPostBack property to true
check.Checked = isChecked; //Set checkbox checked based on status ;
}
else if (row.Cells[row.Cells.Count - 2].Text.Equals("Not yet validated"))
{
isChecked = false;
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox; //position Check column on last row in gridview
check.Enabled = true;
check.CheckedChanged += ValidateSubject_Click; //Bind the event on the button
check.AutoPostBack = true; //Set the AutoPostBack property to true
check.Checked = isChecked; //Set checkbox checked based on status ;
}
}
In this function, the condition above will not changed the database, instead it will only refresh the page when checkbox is clicked.
protected void ValidateSubject_Click(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow grvRow = (GridViewRow)chk.NamingContainer;//This will give row
string validated = "Validated";
string notyetvalidated = "Not yet validated";
string studid = grvRow.Cells[0].Text;
string coursenum = grvRow.Cells[1].Text;
if (chk.Checked)
{
grvRow.Cells[10].Text = validated;
//Open Connection
using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SAD;Integrated Security=True"))
{
//Open Connection to database
try
{
conn.Open();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
using (SqlCommand cmd = new SqlCommand("Update AssessmentForm set Status = #Validated where StudentID = #studentID and CourseNo = #Coursenumber" ,conn))
{
cmd.Parameters.AddWithValue("#Validated", validated);
cmd.Parameters.AddWithValue("#studentID", studid);
cmd.Parameters.AddWithValue("#Coursenumber", coursenum);
cmd.ExecuteNonQuery();
}
//Close Connection to database
try
{
conn.Close();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
}
}
else
{
grvRow.Cells[10].Text = notyetvalidated;
//Open Connection
using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SAD;Integrated Security=True"))
{
//Open Connection to database
try
{
conn.Open();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
//query database to update the Status
using (SqlCommand cmd = new SqlCommand("Update AssessmentForm set Status = #Validated where StudentID = #studentID and CourseNo = #Coursenumber", conn))
{
cmd.Parameters.AddWithValue("#Validated", notyetvalidated);
cmd.Parameters.AddWithValue("#studentID", studid);
cmd.Parameters.AddWithValue("#Coursenumber", coursenum);
cmd.ExecuteNonQuery();
}
//Close Connection to database
try
{
conn.Close();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
}
}
}
You need to modify your Page_Load method in the section where you are iterating inside gridview rows and assigning handlers and setting checkbox property.
In gridview the status column I guess you are saving it at text not a bit so I compared it as text. See following and implement same.
foreach (GridViewRow row in ValidateSubject.Rows)
{
bool isChecked = default(bool);
if (row.Cells[row.Cells.Count - 1].Text.Equals("Validated")) // Here please assign the position of **Status** column.
isChecked = true;
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox; //position Check column on last row in gridview
check.Enabled = true;
check.CheckedChanged += ValidateSubject_Click; //Bind the event on the button
check.AutoPostBack = true; //Set the AutoPostBack property to true
check.Checked = isChecked //Set checkbox checked based on status ;
}
I have tried many things but its just showing error "Object reference not set to an instance of an object."
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
else if (Session["StudId"] != null)
{
Label1.Text = Session["StudId"].ToString();
}
I have written this code in my login page dragging all the required databases strings i.e. typeid,students,faculty,admin and accemployee in the page.
public partial class Login : System.Web.UI.Page
{private string strcon = WebConfigurationManager.ConnectionStrings["StudentConnectionString1"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Cookies["UName"] != null)
TextBox1.Text = Request.Cookies["UName"].Value;
if (Request.Cookies["PWD"] != null)
TextBox2.Attributes["value"] = Request.Cookies["PWD"].Value;
if (Request.Cookies["UName"] != null && Request.Cookies["PWD"] != null)
CheckBox1.Checked = true;
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem.Value == "1")
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select StudFirstName from Student where StudId=#sid and Password=#pw", con);
cmd.Parameters.AddWithValue("#sid", TextBox1.Text);
cmd.Parameters.AddWithValue("#pw", TextBox2.Text);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (String.IsNullOrEmpty(name))
Label1.Text = "Sorry! Invalid User ID or Password!";
else
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = TextBox1.Text;
Response.Cookies["PWD"].Value = TextBox2.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
}
Session.Add("StudId", TextBox1.Text);
Session.Add("StudFirstName", name);
Session.Add("Password", TextBox2.Text);
FormsAuthentication.RedirectFromLoginPage(name, false);
}
}
else if (DropDownList1.SelectedItem.Value == "2")
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select FacultyFirstName from Faculty where FacultyId=#fid and Password=#pw", con);
cmd.Parameters.AddWithValue("#fid", TextBox1.Text);
cmd.Parameters.AddWithValue("#pw", TextBox2.Text);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (String.IsNullOrEmpty(name))
Label1.Text = "Sorry! Invalid User ID or Password!";
else
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = TextBox1.Text;
Response.Cookies["PWD"].Value = TextBox2.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
}
Session["FacultyId"] = TextBox1.Text;
Session.Add("FacultyFisrtName", name);
Session["Password"] = TextBox2.Text;
FormsAuthentication.RedirectFromLoginPage(name, false);
}
}
else if (DropDownList1.SelectedItem.Value == "3")
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select AccEmployeeName from AccEmployee where AccEmployeeId=#aid and Password=#pw", con);
cmd.Parameters.AddWithValue("#aid", TextBox1.Text);
cmd.Parameters.AddWithValue("#pw", TextBox2.Text);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (String.IsNullOrEmpty(name))
Label1.Text = "Sorry! Invalid User ID or Password!";
else
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = TextBox1.Text;
Response.Cookies["PWD"].Value = TextBox2.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
}
Session["AccEmployeeFacultyId"] = TextBox1.Text;
Session.Add("AccEmployeeName", name);
Session["Password"] = TextBox2.Text;
FormsAuthentication.RedirectFromLoginPage(name, false);
}
}
else if (DropDownList1.SelectedItem.Value == "4")
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select from Admin where AdminId=#pid and Password=#pw", con);
cmd.Parameters.AddWithValue("#pid", TextBox1.Text);
cmd.Parameters.AddWithValue("#pw", TextBox2.Text);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (String.IsNullOrEmpty(name))
Label1.Text = "Sorry! Invalid User ID or Password!";
else
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = TextBox1.Text;
Response.Cookies["PWD"].Value = TextBox2.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
}
string adminName = "Pujan";
Session["AdminId"]=TextBox1.Text;
Session["AdminName"] = adminName;
Session["Password"]=TextBox2.Text;
FormsAuthentication.RedirectFromLoginPage(name, false);
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label2.Text = DropDownList1.SelectedItem.Text;
}
`
}
.....................................................................................
Now the error occurs in the masterpage.master.cs which is shown below....
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["StudId"] == null)
Response.Redirect("Login.aspx");
else if (Session["StudId"] != null)
{
Label1.Text = Session["StudId"].ToString();
}
else if (Session["FacultyFirstName"] == null)
{
Response.Redirect("Login.aspx");
}
else if (Session["FacultyFirstName"] != null)
{
Label1.Text = Session["FacultyFirstName"].ToString();
}
else if (Session["AccEmployeeName"] == null)
{
Response.Redirect("Login.aspx");
}
else if (Session["AccEmployeeName"] != null)
{
Label1.Text = Session["AccEmployeeName"].ToString();
}
else if (Session["AdminName"] == null)
{
Response.Redirect("Login.aspx");
}
else if (Session["AdminName"] != null)
{
Label1.Text = Session["AdminName"].ToString();
}
}
protected void LinkButton1_Click1(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect("Login.aspx");
}
}
Please suggest me how to get rid of the error in session or wateva it is......Thank you in advance :)
System.NullReferenceException: Object reference not set to an instance of an object.
This error means that the value that is being provided is a null and the Server cannot use it for a process, that requires a parameter to work on.
Sometimes this happens when you're trying to use a variable in a method, and the variable gets a null value. Null value means that there is no value or no data for this thing.
In your code I guess that this error would generate when the site is first loading. At that time, there is no Session for the Server to load or work on. Thus the values are all null throwing this Null exception.
You can try to cover up the code inside an if else block to check whether there is a cookie present for the Session, or try out a try catch block to minimize this exception and do the work depending on the condition.
An example would be:
try {
/* your code here */
} catch (System.NullReferenceException) {
/* create a session or fill up the variable */
}
This block would run the code of yours, and if the exception provided inside the Catch method gets thrown it would execute the code inside the catch block.
Second thing was to use if else:
if(variable != null) {
/* your code here */
} else {
/* set the value */
}
You just check for the value of that particular variable, and check it. If its a null valued variable, then you can skip the execution of the code block and fill the variable with a value and then come back to the current space and re-execute it.
For exception details: http://msdn.microsoft.com/en-us/library/system.nullreferenceexception(v=vs.110).aspx
I am trying to update a gridview on asp.net using a stored procedure but it always resets to the original values. What am I doing wrong?
edit: all page code added now
protected void page_PreInit(object sender, EventArgs e)
{
MembershipUser UserName;
try
{
if (User.Identity.IsAuthenticated)
{
// Set theme in preInit event
UserName = Membership.GetUser(User.Identity.Name);
Session["UserName"] = UserName;
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
//to edit grid view
protected void GridViewED_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewED.EditIndex = e.NewEditIndex;
}
protected void GridViewED_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_UpdateRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
command.Parameters.Add("#PostalAddress", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
command.Parameters.Add("#TelephoneNo", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
command.Parameters.Add("#Website", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
command.Parameters.Add("#Email", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
}
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
command.ExecuteNonQuery();
MyConnection.Close();
GridViewED.EditIndex = -1;
}
I suspect the code loading the grid is being invoked upon postback, which is causing the data to be pulled from the database when you don't want it to.
Yes - I think you want the code to only load if it is not a postback. You can use the Page.IsPostBack property for this.
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
if (!IsPostBack) {
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
}
Don't bind your data in the Page_Load event. Create a separate method that does it, then in the Page Load, if !IsPostback, call it.
The reason to perform the databinding is it's own method is because you'll need to call it if you're paging through the dataset, deleting, updating, etc, after you perform the task. A call to a method is better than many instances of the same, repetitive, databinding code.
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.