Access a string value outside PageLoad(if(!Page.IsPostBack)) - c#

I want to access value of a string outside the block of if(!Page.IsPostBack) in PageLoad.
I have declared string sap1 public.
My Code is
public partial class WebForm4 : System.Web.UI.Page
{
DateTime d = DateTime.Now;
string sap = "";
string sap1;
protected void Page_Load(object sender, EventArgs e)
{
//DateTime d = DateTime.Now;
TextBox1.Text = d.ToShortDateString();
if (!Page.IsPostBack)
{
string q = d.ToShortDateString();
string[] separators = { "-", "/" };
string s = d.ToShortDateString();
string[] words = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var word in words)
sap = sap + word;
string constr = ConfigurationManager.ConnectionStrings["myString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
sap1 = "D" + sap;
string query = "create table " + sap1 + " (Name varchar(50),ContentType
nvarchar(200),Data varbinary(MAX));";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
AddNewRow();
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(sap1);
}
}
I want to access the value of sap1 outside the PageLoad. I want to use it for insert into Query.

You'll need to store the value of sap1 in a Session
Session["sap1"] = sap1;
Then retrieve it when you need it:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(Session["sap1"]);
}

You have to have some declaration of this property outside of the Page_Load method
private string sap1;
and then you can access it in whole class. But be careful about ASP.NET page life cycle. You will have sap1 with value only after Page_Load. In the earlier stages of the page life cycle it will be null of course.

The problem is the if check if(!Page.IsPostback). You need to calculate sap and sap1 on every PostBack. So it'll available when you click on the button.
Just remove the condition if(!Page.IsPostback).

Related

Cannot retrieve value of Textbox on Update method

I want to update this form's Login and Logout Time:
My code is :
protected void btnUpdate_Click(object sender, EventArgs e)
{
string LoginTime = txtIn.Text;
string LogOutTime = txtOut.Text;
long DayLogId = Convert.ToInt64(Request.QueryString["ID"]);
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =#"Data Source=DELL\SQLSERVER1;Initial Catalog=LoginSystem;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("UPDATE [DayLog] SET [LoginTime]=#LoginTime,[LogOutTime]=#LogOutTime WHERE [DayLogId]=#DayLogId");
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#LoginTime", LoginTime);
dataCommand.Parameters.AddWithValue("#LogOutTime", LogOutTime);
dataCommand.Parameters.AddWithValue("#DayLogId", DayLogId);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
At the first two lines of method ,
string LoginTime = txtIn.Text;
string LogOutTime = txtOut.Text;
when I debug , it does not show the value that I reinserted. This code works if I mannually write
string LoginTime = "11:44:11";
string LogOutTime = "12:44:11";
NOTE:
The value of forms in text box is coming from another page GridView.
protected void grdEmployee_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
GridViewRow grRow = ((Control)e.CommandSource).NamingContainer as GridViewRow;
Label DayLogId = grRow.FindControl("lblDayLogId") as Label;
if (Convert.ToInt16(DayLogId.Text) > 0)
{
Response.Redirect("~/Employee/OutLog_Day.aspx?ID=" + DayLogId.Text, false);
}
}
}
You should make sure that the text box gets populated before the click event runs. As Steve suggested, usually you get this when you initialize the data on every postback which is unnecessary if the data is not changed.

Session name is not retrieved in master page

i using a single master page in asp.net for log-In and Log-Out functionality...
but in master page session name takes null value.
Here is my code ,please help me...
MasterPage.master.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["name"] == null)
{
Panel2.Visible = false;
Panel1.Visible = true;
}
else if (Session["name"] != null)
{
Panel1.Visible = false;
Panel2.Visible = true;
Label2.Text = "WELCOME | Mr." + Session["name"].ToString();
}
}
}
protected void LoginStatus1_LoggedOut(object sender, EventArgs e)
{
Session.Clear();
Session.Abandon();
}
my homepage.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
string st="select Label4,Label3 FROM Register1_master WHERE Label4='" + TextBox1.Text + "' and Label3='" + TextBox2.Text + "'";
cmd = new SqlCommand(st, sqlcon);
cmd.Connection.Open();
string result= null;
Object value=cmd.ExecuteScalar ();
if ( value != null)
{
result = value.ToString ();
Session["name"] = TextBox1.Text;
Response.Redirect("Main.aspx");
}
else
{
Label3.Text="Invalid username or password";
}
cmd.Connection.Close();
}
after the login from homepage i'll be go on Main.aspx page
my Main.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HyperLink link = (HyperLink)Master.FindControl("HyperLink1");
link.Visible = false;
HyperLink link1 = (HyperLink)Master.FindControl("HyperLink2");
link1.Visible = true;
Label masterlbl = (Label)Master.FindControl("Label2");
string login = Convert.ToString(Session["name"]);
Session["name"] = login;
}
}
Have you try like this :
int result= null;
result= = Convert.ToInt32(cmd.ExecuteScalar());
Use the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the ExecuteReader method, and then performing the operations that you need to generate the single value using the data returned by a SqlDataReader.
A typical ExecuteScalar query can be formatted as in the following C# example:
cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
Int32 count = (Int32) cmd.ExecuteScalar();
Please refer MSDN

null value in asp.net page.items

I have an asp.net page with behind C# code.
I add a page Item in main page. then I used some web user control.
In one of them, when I use this Item in page_load. it has correct value, but when I use it in another private function in same web control, it has null value!
then I prefered to use a public string and set the value of that Item in it. but not working too.
public string ReqID0;
string Status0 { get; set; }
string Status = "";
string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection sqlc4;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ReqID0 = Page.Items["ReqID"].ToString();
ReqIDLbl.Text = ReqID0;
...
second function (method) is:
private void Change_Status(string newStatus)
{
//ReqID0=Page.Items["ReqID"].ToString();
sqlc4 = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Request SET Status=#newStatus WHERE ID=#ReqID";
cmd.Parameters.AddWithValue("#newStatus", newStatus);
cmd.Parameters.AddWithValue("#ReqID", ReqID0);
cmd.Connection = sqlc4;
sqlc4.Open();
cmd.ExecuteNonQuery();
sqlc4.Close();
}
Page.Item refreshes with each post back and you have to add it every time your page refreshes ,,and as per your code here in Page_Load event
if (!this.IsPostBack)
{
ReqID0 = Page.Items["ReqID"].ToString();
ReqIDLbl.Text = ReqID0;
--Assigning of value is getting bypassed when your page does a post back and you get Null value in your Change_Status method. Try using Viewstate Instead.
Use the Items property to store objects with the same lifetime as the page request. MSDN
Update: try using ViewState.
if (!this.IsPostBack)
{
ViewState["ReqID"]= ReqIDLbl.Text;
//ReqID0 = Page.Items["ReqID"].ToString();
//ReqIDLbl.Text = ReqID0;
private void Change_Status(string newStatus)
{
//ReqID0=ViewState["ReqID"].ToString();
The global variables are created / intialized between postback in asp.net and they do not retain the values between postback as http is stateless protocol, you need to use ViewState for that.
public string ReqID0;
string Status0 { get; set; }
string Status = "";
string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection sqlc4;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ReqIDLbl.Text = ReqID0;
ReqID0 = ViewState["ReqID0"].ToString();//ViewState
/*In case if the above code doesn't work use
ReqIDLbl.Text = ViewState["ReqID0"].ToString();*/
------
}
//Second Function
private void Change_Status(string newStatus)
{
ReqID0=ViewState["ReqID0"].ToString();
sqlc4 = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Request SET Status=#newStatus WHERE ID=#ReqID";
cmd.Parameters.AddWithValue("#newStatus", newStatus);
cmd.Parameters.AddWithValue("#ReqID", ReqID0);
cmd.Connection = sqlc4;
sqlc4.Open();
cmd.ExecuteNonQuery();
sqlc4.Close();
}
Hope This might give you the answer

c# - How to maintain values in user control when read from database?

I want to maintain user control values in view state
I tried but values are removed
Code:
In the below code I read the values from database and load it in user controls,it's working but if I want to add one more user control when click add button those values are removed
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (OleDbCommand cmd = new OleDbCommand("Select * from visa_details where emp_id = '" + empid + "'", DbConnection))
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
OleDbDataReader DR1 = cmd.ExecuteReader();
while (DR1.Read())
{
string visaNumb = DR1[2].ToString();
string visaCountry = DR1[3].ToString();
string visaType = DR1[4].ToString();
string visaEntry = DR1[5].ToString();
string expiryDate = DR1[6].ToString();
expiryDate = DateTime.Parse(expiryDate).ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture);
VisaUserControl userconrol = (VisaUserControl)Page.LoadControl("VisaUserControl.ascx");
userconrol.TextVisaNumber = visaNumb;
userconrol.VisaCountry = visaCountry;
userconrol.VisaType = visaType;
userconrol.VisaEntry = visaEntry;
userconrol.ExpiryDate = expiryDate;
rpt1.Controls.Add(userconrol);
}
}
}
}
Below code is for adding user control when click add button
public List<string> NoOfControls
{
get
{
return ViewState["NoOfControls"] == null ? new List<string>() : (List<string>)ViewState["NoOfControls"];
}
set
{
ViewState["NoOfControls"] = value;
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
GenerateControls();
}
private void GenerateControls()
{
foreach (string i in NoOfControls)
{
VisaUserControl ctrl = (VisaUserControl)Page.LoadControl("VisaUserControl.ascx");
ctrl.ID = i;
this.rpt1.Controls.Add(ctrl);
}
}
protected void btnAddVisa_Click(object sender, EventArgs e)
{
List<string> temp = null;
var uc = (VisaUserControl)this.LoadControl(#"VisaUserControl.ascx");
string id = Guid.NewGuid().ToString();
uc.ID = id;
temp = NoOfControls;
temp.Add(id);
NoOfControls = temp;
rpt1.Controls.Add(uc);
}
In the below image if I click Add More Visa button those values and controls are removed I want to persist those values
Any ideas? Thanks in advance
The fact is that when you click the button, the page does a postback, therefore the part of your code in the Page_Load event inside the if (!IsPostBack) condition is not executed.
This includes the creation of the VisaUserControl, which you are creating dynamically.

I want to search a user inputed string in a database and display all possible results

A user inputs a keyword into a textbox which must be searched in the database which is connected to c# using Connection String, I want to search in the database and display all the possible occurrence of the keyword which the user inputs.
After clicking the button, I get the error message "Object reference not set to an instance of an object" which points to the line "ResultsQuery = Request.QueryString[TextBox1.Text].Split(' ');"
public string[] ResultsQuery;
public int i;
public string criteria;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string connString = #"Data Source=ITLAPTOP\SQLEXPRESS;Initial Catalog=trial;Integrated Security=True";
SqlConnection connStudent = new SqlConnection(connString);
connStudent.Open();
ResultsQuery = Request.QueryString[TextBox1.Text].Split(' ');
foreach (string textbox1 in ResultsQuery)
{
if(!string.IsNullOrEmpty(criteria))
criteria +=" OR ";
criteria += "SearchName LIKE '%" + textbox1 + "%' ";
}
string SqlInsertStatement = #"select * from trial.dbo.Student where Student.SearchName where '" + criteria;
SqlCommand cmdTxt = new SqlCommand(SqlInsertStatement, connStudent);
SqlDataReader dtrACode = cmdTxt.ExecuteReader();
dtrACode.Read();
try
{
if ((dtrACode["SearchName"].ToString().Trim().Length != 0))
{
}
ListBox1.Items.Add(dtrACode["SearchName"].ToString());
}
catch (Exception)
{
ListBox1.Items.Add("NO RECORD FOUND!");
}
connStudent.Close();
connStudent.Dispose();
}
Check to see if the query string value exists before you try and retrieve it, like this:
if (Request.QueryString[TextBox1.Text] != null) {
ResultsQuery = Request.QueryString[TextBox1.Text].Split(' ');
}

Categories