else error occur in asp.net - asp.net

I am trying approving documents and below is the code in button which I did it
but here else condition error occur ..any one tell me where is the mistake occur in below code. Is there nay brackets problem or something else????
code
protected void Button1_Click(object sender, EventArgs e)
{
string connStr =
ConfigurationManager.ConnectionStrings["mydms"].ConnectionString;
SqlConnection mySQLconnection = new SqlConnection(connStr);
if (mySQLconnection.State == ConnectionState.Closed)
{
mySQLconnection.Open();
}
for (int i = 0; i < Repeater2.Items.Count; i++)
{
DropDownList DropDownListcontrol =
((DropDownList)Repeater2.Items[i].FindControl("DropDownList4"));
Label DocId = ((Label)Repeater2.Items[i].FindControl("DocId"));
SqlCommand cmd = new SqlCommand("approveddd",mySQLconnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#DocID", SqlDbType.Int).Value =
Convert.ToInt32((DocID.Text));
cmd.Parameters.Add("#ApproveID", SqlDbType.Int).Value =
Convert.ToInt32(DropDownListcontrol.SelectedValue);
cmd.Parameters.Add("#ApproveBy", SqlDbType.VarChar, 50).Value
= (Session["Login2"]);
cmd.ExecuteNonQuery();
DMSLIB.Doc myDoc = new DMSLIB.Doc();
myDoc.MarkDocAs(Convert.ToInt16(DocId.Text),
Convert.ToInt32(DropDownListcontrol.SelectedValue));
}
else
{
apfi.Text = "Error";
}
if (mySQLconnection.State == ConnectionState.Open)
{
mySQLconnection.Close();
}
}
An error occurs in the else block:
Invalid expression term 'else'
; expected

You must follow Microsoft guideline . It should be like this :
if(condition)
{
}
else
{
}
Not like this
if(condition)
{
}
for(...........)
{
}
else
{
}

You misplaced else. change your for loop. because you have
if()
{
}
for()
{
}
else// belongs to where?
{
}

Related

Stored procedure executing even with the error message

I'm working with two stored procedures in an ASP.NET button function. While I get an error message based on the results that the invoice number is already dispatched from the other stored procedure, it still moves to the other stored procedure and executes it.
If the user gets this error message:
This invoice num was already dispatched!
then it shouldn't move on to this aspect of the function
protected void Button2_Click(object sender, EventArgs e)
{
try
{
for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
{
var row = GridView2.Rows[i];
CheckBox chk = row.FindControl("chkInvoice") as CheckBox;
//CheckBox chk = (CheckBox)GridView2.Rows[i].Cells[0].FindControl("CheckBox3");
if (chk != null && chk.Checked)
{
string strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();
using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
{
objConnection.Open();
using (SqlTransaction transaction = objConnection.BeginTransaction())
{
string SID = GridView2.Rows[i].Cells[3].Text.Trim();
SqlDataReader myReader = null;
using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#invoiceNum", SID);
command.Parameters.AddWithValue("#custPONum", GridView2.Rows[i].Cells[4].Text.Trim());
myReader = command.ExecuteReader();
if (myReader.Read())
{
string invoice1 = (myReader["status"].ToString());
if (invoice1 == "0")
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
}
myReader.Close();
}
}
else if (invoice1=="1")
{
using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#loadSheetNum", txtDispatchNum.Text);
cmd.Parameters.AddWithValue("#invoiceNum", SID);
cmd.Parameters.AddWithValue("#removeUser", lblUsername.Text.Replace("Welcome", ""));
**int a = cmd.ExecuteNonQuery();**
cmd.Dispose();
if (a > 0)
{
dt.Rows.RemoveAt(i);
////Read invoice qty from grid view 2
string invoice = GridView2.Rows[i].Cells[5].Text.ToString();
decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
txtInvoiceTotal.Text = invoiceTotal.ToString();
////Read invoice weight from grid view 2
string weight = GridView2.Rows[i].Cells[6].Text.ToString();
decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
txtQtyWeight.Text = invoiceWeight.ToString();
lblError.ForeColor = Color.Green;
lblError.Text = "Selected record(s) successfully updated";
}
else
{
lblError.ForeColor = Color.Red;
lblError.Text = " Record has not yet been recorded";
}
}
//objConnection.Close();
transaction.Commit();
}
}
}
//Button2.Visible = false;
//showData();
GridView2.DataSource = dt;
GridView2.DataBind();
txtInvoiceCount.Text = dt.Rows.Count.ToString();
}
}
}
catch (Exception ex)
{
if (ex.Message.StartsWith("Violation of PRIMARY KEY constraint"))
{
lblError.ForeColor = Color.Red;
lblError.Text = " This invoice number was remove from dispatch sheet before!!";
}
else
{
// re-throw the error if you haven't handled it
lblError.Text = ex.Message;
throw;
}
}
}
You have a very, very simple logic error, but it is incredibly hard to see because your code is such a mess. Therefore, my answer is:
REFACTOR REFACTOR REFACTOR
It is important to get into the habit of writing short functions and controlling their inputs and outputs. If you don't do this, even a fairly trivial operation like this one gets very confusing and error-prone.
Here is an example of how to organize things. We remove most of the code from the click handler:
protected void DeleteButton_Click(object sender, EventArgs e)
{
for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
{
var row = GridView2.Rows[i];
if (IsChecked(row))
{
var result = ProcessRow(row, i);
DisplayResult(i, result);
}
}
}
Firstly, notice it has a meaningful name. These become very important as your application grows. Also, look how short it is! Where did all the code go? Well, it went into two separate methods, which are now short enough for us to view on one page-- a common requirement that IT organizations impose on their programmers, to avoid spaghetti code.
protected TransactionResult ProcessRow(GridViewRow row, int index)
{
var SID = GridView2.Rows[index].Cells[3].Text.Trim();
var custPONum = GridView2.Rows[index].Cells[4].Text.Trim();
var loadSheetNum = txtDispatchNum.Text;
var removeUser = lblUsername.Text.Replace("Welcome", "");
return ExecuteInvoiceTransaction(SID, custPONum, loadSheetNum, removeUser);
}
And
public void DisplayResult(int rowIndex, TransactionResult result)
{
switch result
{
case TransactionResult.Success:
dt.Rows.RemoveAt(rowIndex);
DisplayTotals(rowIndex);
DisplaySuccess("Selected record(s) successfully updated");
break;
case TransactionResult.AlreadyDispatched;
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
break;
case TransactionResult.RecordNotRecorded;
DisplayError("Record has not yet been recorded");
break;
case TransactionResult.AlreadyRemoved:
DisplayError("This invoice number was remove from dispatch sheet before!!");
break;
}
}
These methods in turn call a variety of helper methods, each of which does one thing and one thing only. This could be referred to as separation of concerns, which is really important for structured code.
Here's the rest of the methods:
enum TransactionResult
{
Success,
AlreadyDispatched,
RecordNotRecorded,
AlreadyRemoved
}
private bool ExecuteSelectStatus(SqlConnection connection, SqlTransaction transaction, string invoiceNum, string custPONum)
{
using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#invoiceNum", invoiceNum);
command.Parameters.AddWithValue("#custPONum", custPONum);
using (var myReader = command.ExecuteReader())
{
if (myReader.Read())
{
string invoice1 = (myReader["status"].ToString());
if (invoice1 == "0")
{
return false;
}
}
}
return true;
}
}
private int ExecuteRemoveInvoice(SqlConnection objConnection, SqlTransaction transaction, string loadSheetNum, string invoiceNum, string removeUser)
{
try
{
using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#loadSheetNum", loadSheetNum);
cmd.Parameters.AddWithValue("#invoiceNum", invoiceNum);
cmd.Parameters.AddWithValue("#removeUser", removeUser);
return cmd.ExecuteNonQuery();
}
}
catch (SqlException ex)
{
if (ex.Number == 2627) //Primary key violation
{
return -1;
}
}
}
protected TransactionResult ExecuteInvoiceTransaction(string invoiceNum, string custPONum, string loadSheetNum, string removeUser)
{
var strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();
using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
{
objConnection.Open();
using (SqlTransaction transaction = objConnection.BeginTransaction())
{
var ok = ExecuteSelectStatus(objConnection, transaction, invoiceNum, custPONum);
if (!ok) return TransactionResult.AlreadyDispatched;
var a = ExecuteRemoveInvoice(objConnection, transaction, loadSheetNum, invoiceNum, removeUser);
switch a
{
case -1:
return TransactionResult.AlreadyRemoved;
case 0:
return TransactionResult.RecordNotRecorded;
default:
transaction.Commit();
return TransactionResult.Success;
}
}
}
}
public void DisplayTotals(int i)
{
////Read invoice qty from grid view 2
string invoice = GridView2.Rows[i].Cells[5].Text;
decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
txtInvoiceTotal.Text = invoiceTotal.ToString();
////Read invoice weight from grid view 2
string weight = GridView2.Rows[i].Cells[6].Text();
decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
txtQtyWeight.Text = invoiceWeight.ToString();
}
public void DisplaySuccess(string message)
{
lblError.ForeColor = Color.Green;
lblError.Text = message;
}
public void DisplayError(string message)
{
lblError.ForeColor = Color.Red;
lblError.Text = message;
}
A few things to note:
You don't need to call Dispose() if you are using using.
You should always catch the most specific exception possible, per Microsoft's guidance. My example does this.
The exception handling for the primary key error is isolated into the method that calls the stored procedure. The overall business logic shouldn't have to know details about the SQL implementation. I've shown how you can identify the specific error based on this post.
Because there are four possible outcomes, I added an enumeration called TransactionResult so we could return the status to the caller easily.
Some of these methods are short-- just two lines-- and that is OK. The main reason to separate them out is to give them a meaningful name and make the code shorter and easier to read.
This code is much more structured but it could still be improved! In many implementations, the code that accesses the database is actually moved to a completely different layer or project.
See if this works. Moved your if/else together:
protected void Button2_Click(object sender, EventArgs e)
{
try
{
for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
{
var row = GridView2.Rows[i];
CheckBox chk = row.FindControl("chkInvoice") as CheckBox;
if (chk != null && chk.Checked)
{
string strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();
using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
{
objConnection.Open();
using (SqlTransaction transaction = objConnection.BeginTransaction())
{
string SID = GridView2.Rows[i].Cells[3].Text.Trim();
SqlDataReader myReader = null;
using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#invoiceNum", SID);
command.Parameters.AddWithValue("#custPONum", GridView2.Rows[i].Cells[4].Text.Trim());
myReader = command.ExecuteReader();
if (myReader.Read())
{
string invoice1 = (myReader["status"].ToString());
if (invoice1 == "0")
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
}
else if (invoice1 == "1")
{
using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#loadSheetNum", txtDispatchNum.Text);
cmd.Parameters.AddWithValue("#invoiceNum", SID);
cmd.Parameters.AddWithValue("#removeUser", lblUsername.Text.Replace("Welcome", ""));
int a = cmd.ExecuteNonQuery();
cmd.Dispose();
if (a > 0)
{
dt.Rows.RemoveAt(i);
////Read invoice qty from grid view 2
string invoice = GridView2.Rows[i].Cells[5].Text.ToString();
decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
txtInvoiceTotal.Text = invoiceTotal.ToString();
////Read invoice weight from grid view 2
string weight = GridView2.Rows[i].Cells[6].Text.ToString();
decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
txtQtyWeight.Text = invoiceWeight.ToString();
lblError.ForeColor = Color.Green;
lblError.Text = "Selected record(s) successfully updated";
}
else
{
lblError.ForeColor = Color.Red;
lblError.Text = " Record has not yet been recorded";
}
}
//objConnection.Close();
transaction.Commit();
}
}
}
GridView2.DataSource = dt;
GridView2.DataBind();
txtInvoiceCount.Text = dt.Rows.Count.ToString();
}
}
}
}
}
catch (Exception ex)
{
if (ex.Message.StartsWith("Violation of PRIMARY KEY constraint"))
{
lblError.ForeColor = Color.Red;
lblError.Text = " This invoice number was remove from dispatch sheet before!!";
}
else
{
// re-throw the error if you haven't handled it
lblError.Text = ex.Message;
throw;
}
}
}
}

asp.net clear row selection for Multiple Grid with Single Button Click

Hi Friends i have created a single asp.net page(c#) with multiple grid view to display records. I have multiple command button to show records in these grid.
I am using single button to clear the row selection in grid but it is not working.
Please help me...
protected void btnClearGridSelection_Click(object sender, EventArgs e)
{
if (GridView1.Visible == true)
{
GridView1.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewSearch.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewState.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewDistrict.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewType.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewEmployee.SelectedIndex = -1;
}
}
//---------------------updating my question with new problem-------------
Now i am able to to clear the selection from row but facing new problem.......When i am clicking on show(to show results state wise) button it is showing results and also clearing the selection when clicking on clear selection button with no problems....but when i click on another show button(to show results district wise) to show results it is showing results but when i select the row and click on clear selection button it is showing both grid with records......please help how to hide state Grid when i am Clicking on Clear Selection Button while using District grid......i am posting the code which i am using on Button Click....
.......clear selection....Button click:
protected void btnClearGridSelection_Click(object sender, EventArgs e)
{ GridView1.SelectedIndex = -1;
GridViewSearch.SelectedIndex = -1;
GridViewState.SelectedIndex = -1;
GridViewDistrict.SelectedIndex = -1;
GridViewType.SelectedIndex = -1;
GridViewEmployee.SelectedIndex = -1;
}
.......State Grid....Button click:
protected void btnState_Click(object sender, EventArgs e)
{
GridView1.Visible = false;
//GridViewState.Visible = true;
GridViewDistrict.Visible = false;
GridViewSearch.Visible = false;
GridViewType.Visible = false;
GridViewEmployee.Visible = false;
btnClearGridSelection.Visible = true;
string d2 = ddlState.Text;
string strquery = "select * from tblAsset2 where v_State=#d2";
if (con.State != ConnectionState.Closed)
{
con.Close();
}
con.Open();
try
{
SqlCommand cmd = new SqlCommand(strquery, con);
cmd.Parameters.AddWithValue("#d2", d2);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridViewState.DataSource = ds;
GridViewState.DataBind();
int rowCount = GridViewState.Rows.Count;
if (rowCount <= 0)
{
Label67.Visible = true;
GridViewState.Visible = false;
Label67.Text = "Sorry!....Records not found.";
}
else
{
GridViewState.Visible = true;
Label67.Visible = false;
}
}
catch (Exception ex)
{
Response.Write(ex);
}
finally
{
con.Close();
}
}
....................District Grid....Button click:
protected void btnDistrict_Click(object sender, EventArgs e)
{
GridView1.Visible = false;
GridViewDistrict.Visible = false;
//GridViewDistrict.Visible = true;
GridViewSearch.Visible = false;
GridViewType.Visible = false;
GridViewEmployee.Visible = false;
btnClearGridSelection.Visible = true;
string d2 = ddlDistrict.Text;
string strquery = "select * from tblAsset2 where v_District=#d2";
if (con.State != ConnectionState.Closed)
{
con.Close();
}
con.Open();
try
{
SqlCommand cmd = new SqlCommand(strquery, con);
cmd.Parameters.AddWithValue("#d2", d2);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridViewDistrict.DataSource = ds;
GridViewDistrict.DataBind();
int rowCount = GridViewDistrict.Rows.Count;
if (rowCount <= 0)
{
Label67.Visible = true;
GridViewDistrict.Visible = false;
Label67.Text = "Sorry!....Records not found.";
}
else
{
GridViewDistrict.Visible = true;
Label67.Visible = false;
}
}
catch (Exception ex)
{
Response.Write(ex);
}
finally
{
con.Close();
}
}
I resolved my problem and it may help someone else so i am posting it.. i have written wrong line:- GridViewState.Visible = true; // i have commented this line and error gone
protected void GridViewState_RowCreated(object sender, GridViewRowEventArgs e)
{
GridViewState.Visible = true; // i have commented this line and error gone
}

using Session for creating login for mutiple users has error and further which can evaluate the rights of users

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

how to return a datatable if a register number exists

I am trying to display a grid if the user entered register number exists in database, if the register number does not exists this means that I need to display one label also.i am a new one in asp.net,so please help me.
Here is my code below.
public DataTable madhrasaViewByRegNo(string viewByNo)
{
try
{
madhrasaInfo infomadhrasa = new madhrasaInfo();
object decobj = new object();
if (sqlcon.State == ConnectionState.Closed)
{
sqlcon.Open();
}
SqlCommand sqlcmd = new SqlCommand("madhrasaViewByRegNo", sqlcon);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.Add("#regNo", SqlDbType.VarChar).Value = viewByNo;
decobj = sqlcmd.ExecuteNonQuery();
if (decobj == null)
{
decStuId = decimal.Parse(decobj.ToString());
}
else
{
DataTable dtbClass = new DataTable();
SqlDataAdapter sqlda = new SqlDataAdapter("madhrasaViewByRegNo", sqlcon);
sqlda.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlda.SelectCommand.Parameters.Add("#regNo", SqlDbType.VarChar).Value = viewByNo;
sqlda.Fill(dtbClass);
return dtbClass;
}
}
catch (Exception)
{
throw;
}
return null;
}
public void gridfillByNo()
{
madhrasaSp spMadhrasa = new madhrasaSp();
DataTable dtbl = new DataTable();
dtbl = spMadhrasa.madhrasaViewByRegNo(TextBox2.Text);
gvstuResult.DataSource = dtbl;
gvstuResult.DataBind();
}
public void regSearch()
{
madhrasaSp spmadhrasa = new madhrasaSp();
spmadhrasa.madhrasaViewByRegNo(TextBox2.Text);
if (madhrasaSp.decStuId > 0)
{
gridfillByNo();
MultiView1.ActiveViewIndex = 1;
}
else
{
MultiView1.ActiveViewIndex = 0;
Label1.Visible = true;
Label1.Text = "Invalid Register Number";
}
}
protected void Button2_Click(object sender, EventArgs e)
{
regSearch();
}
You Dont you just set the grid view's EmptyDataText to 'Reg No Dosent exist'. It will solve your ploblem.
<asp:GridView ID="GridView1" runat="server" EmptyDataText="register number not available">
</asp:GridView>

update cancel on gridview asp.net

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.

Resources