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

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.

Related

My list session is not retriving the right value

I have a list to save the orders the client had selected and i wanted to pass the values on the list to other page so i was trying to use
HttpContext.Current.Session["list"] = MySelected;
but I am not getting the values in my other page.
order page:
protected void ButtonCreate_Click(object sender, EventArgs e)
{
string MyPkList = string.Join(",", MySelected);
SqlCommand cmdSQLCount = new SqlCommand("select Count(*) from [EncomendaTEMP] where No_ IN(" + MyPkList + ")", con);
cmdSQLCount.Connection.Open();
int qtd = 0;
SqlDataReader reader = cmdSQLCount.ExecuteReader();
while (reader.Read())
qtd = reader.GetInt32(0);
if (qtd > 0)
{
HttpContext.Current.Session["list"] = MySelected;
Response.Redirect("Booking.aspx", false);
}
else
{
Response.Write("<h2> Nenhum registo encontrado! </h2>");
}
Booking page:
protected void Page_Load(object sender, EventArgs e)
{
var list = HttpContext.Current.Session["list"];
Response.Write("<h2> PK = "+list+" </h2>");
}
returns:
To get join value of element in List<string>, try:
var list = HttpContext.Current.Session["list"] as List<string>;
string items = string.Join(",", list);
from #Chetan Ranpariya 's comment.

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

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).

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.

Sql data reader wont return my values to objects

I have this code that gets the return query from SQL and place it in Labels. The problem is, when I click the Search Button, The Labels wont populate. but when I enter debug mode, It has values. Why is that?! help!
//I've cut down the code here to make the question clearer
//But these 4 fields were all valid properties - Sayse
public string FirstName
public string MiddleName
public string LastName
public string Email
public void SearchAffectedUser()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand com_retrieve = new SqlCommand("Reader.usp_SearchAffectedUser", con))
{
com_retrieve.CommandType = CommandType.StoredProcedure;
com_retrieve.Parameters.Add("#fld_EmployeeId", SqlDbType.Int).Value = AffectedUser;
con.Open();
com_retrieve.ExecuteNonQuery();
SqlDataReader dr = com_retrieve.ExecuteReader();
if (dr.Read())
{
FirstName = dr.GetValue(0).ToString();
MiddleName = dr.GetValue(1).ToString();
LastName = dr.GetValue(2).ToString();
Email = dr.GetValue(3).ToString();
}
}
}
}
protected void findAffectedUserButton_Click(object sender, EventArgs e)
{
ticket.AffectedUser = affectedUserTextBox.Text;
ticket.FirstName = firstNameValueLabel.Text;
ticket.MiddleName = middleNameValueLabel.Text;
ticket.LastName = lastNameValueLabel.Text;
ticket.Email = emailValueLabel.Text;
ticket.SearchAffectedUser();
}
First set the AffectedUser property used for the search then call the search command and finally set the labels.
protected void findAffectedUserButton_Click(object sender, EventArgs e)
{
ticket.AffectedUser = affectedUserTextBox.Text;
ticket.SearchAffectedUser();
firstNameValueLabel.Text = ticket.FirstName;
middleNameValueLabel.Text = ticket.MiddleName;
lastNameValueLabel.Text = ticket.LastName;
emailValueLabel.Text = ticket.Email;
}
set label TEXT property to "".

save username but shows name in c#

I'm working with c#, in vs 2008, framework 3.5, I need to save the username and when
the user log in, it shows he/her first and last name, at this point can save it, and
that is what I want but need to show to the user not his/her username just the first and
last name. here is my code, thanks in advance.
//code in the login
ClPersona login = new ClPersona();
bool isAuthenticated = login.sqlLogin1((txtUsuario.Text), (txtPassword.Text));
if (isAuthenticated)
{
Session["sesionicontrol"] = login.NombreUsuario;
Response.Redirect("../MENU/menu1.aspx");
}
//code in the form where shows the username but I want the first and last name
public partial class menu2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblNombreUsuario.Text = (string)Session["sesionicontrol"];
if (!IsPostBack)
//ClPersona class
public Boolean sqlLogin1(string nombreUsuario, string password)
{
string stSql = "select * from usuarios where usuario='" + nombreUsuario + "' and
pass='" + password + "'and id_rol='1'";
Bd miBd = new Bd();
DataTable dt = miBd.sqlSelect(stSql);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
//return ds;
if (dt.Rows.Count > 0)
{
return true;
}
else
{
return false;
}
}
Modify two sections
First
if (isAuthenticated)
{
Session["YouObject"] = login;//<--
Session["sesionicontrol"] = login.NombreUsuario;
Response.Redirect("../MENU/menu1.aspx");
}
Second
protected void Page_Load(object sender, EventArgs e)
{
if(Session["YouObject"] != null)
{
ClPersona obj = (ClPersona )Session["YouObject"];
lblNombreUsuario.Text = string.Format("{0}-{1}", obj.FirstName, obj.LastName )
}
lblNombreUsuario.Text = (string)Session["sesionicontrol"];
....
}

Categories