I want to take the DateTime of the user's connection. I guess I will use the Session variable because I don't want that the DateTime changes at every refresh of my page.
Maybe something like that :
void Session_Start(object sender, EventArgs e)
{
Session["dateandhour"] = DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + "." + DateTime.Now.Hour + "." + DateTime.Now.Minute + "." + DateTime.Now.Second;
}
protected void Page_Load(object sender, EventArgs e)
{
string hour= (string)(Session["dateandhour"]);
lab10.Text = hour;
}
You can save the DateTime directly:
void Session_Start(object sender, EventArgs e)
{
Session["dateandhour"] = DateTime.Now;
}
protected void Page_Load(object sender, EventArgs e)
{
DateTime time = (DateTime)(Session["dateandhour"]);
lab10.Text = time.Hour;
}
This greatly simplifies subsequent use of the data.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to add 3 textboxes into 1 label.
And not only that but first the combobox is going to add dear mr / dear miss then when i want to type in the textboxes it should come behind that.
This is the code I have been working with:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "Man")
lblAanhef.Text = "Geachte heer " + txtVnaam.Text +" "+ txtTvoegsel.Text + " " + txtAnaam.Text;
else
lblAanhef.Text = "Geachte mevrouw";
}
private void fOpdracht1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("Man");
comboBox1.Items.Add("Vrouw");
}
private void txtVnaam_TextChanged(object sender, EventArgs e)
{
}
private void txtTvoegsel_TextChanged(object sender, EventArgs e)
{
}
private void txtAnaam_TextChanged(object sender, EventArgs e)
{
}
I have been struggling with this all morning but i cant seem to figure out how to do it.
If anyone knows please let me know.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
changeText();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
changeText();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
changeText();
}
private void changeText()
{
if (comboBox1.SelectedItem.ToString() == "Man")
label1.Text = "Geachte heer " + textBox1.Text + " " + textBox2.Text;
else
label1.Text = "Geachte mevrouw " + textBox1.Text + " " + textBox2.Text;
}
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = "";
comboBox1.Items.Add("Man");
comboBox1.Items.Add("Woman");
comboBox1.SelectedIndex = 0;
}
Like this?
I'm learning ASP.NET and I don't understand what is going on here.
The code behind file:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "Some more text";
TextBox1.ForColor = System.Drawing.Color.Blue;
}
Essentially all there is just a label that tells you what the color and text of the textbox is. When you hit the button it changes the color to blue, and the page reloads.
Why is it that when you press the button the first time and the page reloads, the label does not update to the correct information? You have to press the button again for it to read that the text box is red.
Can anyone provide an explanation for this behavior? And how to change the Page_Load method to fix this issue?
The Page_Load event is being handled before the control events. See the description of the page lifecycle at http://msdn.microsoft.com/en-us/library/ms178472.aspx. To fix it, modify the code so that both Page_Load and the Button_Click handlers call the same method to set the label value. Only have Page_Load execute if the method isn't a POSTBACK.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetUpLabel();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "Some more text";
TextBox1.ForeColor = System.Drawing.Color.Blue;
SetUpLabel();
}
private void SetUpLabel()
{
Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
}
You Need To Write The Code In Page_Load As Under:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) //This condition allows a code to execute once when your page is load first time.
{
Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "Some more text";
TextBox1.ForColor = System.Drawing.Color.Blue;
Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
}
try it, Simply try this code, this codes alway's work, don't need extra code
bool IsClick=false;
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
if(IsClick)
{
TextBox1.Text = "Some more text";
TextBox1.ForeColor = System.Drawing.Color.Blue;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
IsClick=true;
}
This is My Idea
Below is my code. I want to capture the difference between two timestamps at two different button clicks, i.e., i want the "startTime" of btnStartTime_click event to be used in btnEndTime_click event.
protected void btnStartTime_Click(object sender, EventArgs e)
{
var startTime = DateTime.Now;
lblStartTime.Text = startTime.ToString("HH:mm:ss tt");
}
protected void btnEndTime_Click(object sender, EventArgs e)
{
var workDuration = DateTime.Now.Subtract(startTime).TotalMinutes;
lblEndTime.Text = ("The Work duration is "+workDuration);
}
Just make your startTime outside the local scope:
DateTime startTime;
protected void btnStartTime_Click(object sender, EventArgs e)
{
startTime = DateTime.Now;
lblStartTime.Text = startTime.ToString("HH:mm:ss tt");
}
protected void btnEndTime_Click(object sender, EventArgs e)
{
var workDuration = DateTime.Now.Subtract(startTime).TotalMinutes;
lblEndTime.Text = ("The Work duration is "+workDuration);
}
Since this concerns a web application, you must store the startTime in a way where it can be restored on a later post back.
Here's a quick sample that should work using ViewState:
private const string StartTimeViewstateKey = "StartTimeViewstateKey";
protected void btnStartTime_Click(object sender, EventArgs e)
{
var startTime = DateTime.Now;
ViewState[StartTimeViewstateKey] = startTime.ToString(CultureInfo.InvariantCulture);
}
protected void btnEndTime_Click(object sender, EventArgs e)
{
var startTime = DateTime.Parse((string)ViewState[StartTimeViewstateKey], CultureInfo.InvariantCulture);
var workDuration = DateTime.Now.Subtract(startTime).TotalMinutes;
lblEndTime.Text = ("The Work duration is " + workDuration);
}
Alternatively you could use session state:
private const string StartTimeSessionKey= "StartTimeSessionKey";
protected void btnStartTime_Click(object sender, EventArgs e)
{
var startTime = DateTime.Now;
Session[StartTimeSessionKey] = startTime;
}
protected void btnEndTime_Click(object sender, EventArgs e)
{
var startTime = (DateTime)Session[StartTimeSessionKey];
var workDuration = DateTime.Now.Subtract(startTime).TotalMinutes;
lblEndTime.Text = ("The Work duration is " + workDuration);
}
In the following I've taken out irrelevant code. I've created a field called printString. The calculateButton_Click method does a heap of stuff, then I want to send it to a print-friendly page using response.write. However the printString variable doesn't seem to ever stop being "DEFAULT". DEFAULT is all that shows up on my blank page when I click the printButton_Click. Trimmed code below:
public partial class _Default : System.Web.UI.Page
{
private string _printString = "DEFAULT";
protected void Page_Load(object sender, EventArgs e)
{
Response.Buffer = true;
}
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "";
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
}
protected void printButton_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
}
When printButton is clicked it is using the value DEFAULT from when the variable is being set.
private string _printString = "DEFAULT";
Is your problem. You need to maintain the state of printString when the variable is modified. Simply assigning _printString to another value is not persisting the change. You could either write a function to assign _printString to the correct value when printButton is clicked, use ViewState or Session or assign _printString in the printButton click function directly as shown below.
protected void printButton_Click(object sender, EventArgs e)
{
_printString = "Harry Potter";
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
Will result in Harry Potter being wrote to the page.
To use Session:
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
Session["PrintString"] = _printString;
}
protected void printButton_Click(object sender, EventArgs e)
{
_printString = (string)Session["PrintString"];
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
ViewState:
ViewState["PrintString"] = "HarryPotter";
Then to retrieve the value you can simply do:
_printString = (string)ViewState["PrintString"];
http://msdn.microsoft.com/en-gb/library/ms972976.aspx
All (instance) variables are disposed at the end of the page's lifecycle since HTTP is stateless(even the controls). You could use a ViewState, HiddenField or Session variable instead.
private string PrintString
{
get
{
if (ViewState["PrintString "] == null || string.IsNullOrEmpty((String)ViewState["PrintString"]))
{
ViewState["PrintString"] = "DEFAULT";
}
return ViewState["PrintString"].ToString();
}
set { ViewState["PrintString"] = value; }
}
There are other options:
Nine Options for Managing Persistent User State in Your ASP.NET Application
The button click event is causing a postback and the _printString value is not being persisted. You need to store it in the calculate method via Session or Viewstate and then set it in the print for example: -
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "";
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
Session["bigstring"] = _printString;
}
protected void printButton_Click(object sender, EventArgs e)
{
Response.Clear();
_printString = Session["bigstring"].ToString();
Response.Write(_printString);
Response.Flush();
Response.End();
}
I have 3 checkboxes with corresponding message in a textbox. My teacher wants the message to remain in the textbox when the checkbox is still checked and hide the text when it is unchecked. In my case when I checked the 3 checkboxes their 3 corresponding messages will appear but when I unchecked one of the checkboxes and the other two are still checked, all the message will disappear. My problem is when I unchecked one of the checkbox and and the other 2 are still checked the corresponding messages with the remaining two checked checkboxes will remain in their textboxes.
private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
{
if (chkCarWheels.Checked == true)
lblMessage.Text = lblMessage.Text + mycar.hasWheels(4);
else
lblMessage.Text = "My " + txtName.Text + " Car";
}
private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
{
if (chkCarAcceleration.Checked == true)
lblMessage.Text = lblMessage.Text + mycar.Accelerate();
else
lblMessage.Text = "My " + txtName.Text + " Car";
}
private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
{
if (chkCarBreakpad.Checked == true)
lblMessage.Text = lblMessage.Text + mycar.hasBreak();
else
lblMessage.Text = "My " + txtName.Text + " Car";
}
Looks like you need to create message depending on checkboxes states. You can create method, which will do the job and call it when state of some checkbox changed.
private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
Or the better one - create one event handler for all checkboxes:
// use for chkCarWheels, chkCarAcceleration, chkCarBreakpad
private void chkCar_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
private void BuildMessage()
{
lblMessage.Text = "My " + txtName.Text + " Car";
if (chkCarWheels.Checked)
lblMessage.Text = lblMessage.Text + mycar.hasWheels(4);
if (chkCarAcceleration.Checked)
lblMessage.Text = lblMessage.Text + mycar.Accelerate();
if (chkCarBreakpad.Checked)
lblMessage.Text = lblMessage.Text + mycar.hasBreak();
}
You don't need to compare boolean values with true/false. Use those values directly if (chkCarWheels.Checked). And keep in mind that in C# we use CamelCase names form methods. Also consider to use StringBuilder to build whole message and then assign it to label:
private void BuildMessage()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("My {0} Car", txtName.Text);
if (chkCarWheels.Checked)
sb.Append(mycar.hasWheels(4));
if (chkCarAcceleration.Checked)
sb.Append(mycar.Accelerate());
if (chkCarBreakpad.Checked)
sb.Append((mycar.hasBreak());
lblMessage.Text = sb.ToString();
}
Try this:
private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
{
chkCar();
}
private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
{
chkCar();
}
private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
{
chkCar()
}
private void chkCar()
{
string msg="";
if (chkCarWheels.Checked)
msg=msg+mycar.hasWheels(4);
if(chkCarAcceleration.Checked)
msg=msg+mycar.Accelerate();
if(chkCarBreakpad.Checked)
msg=msg+mycar.hasBreak();
lblMessage.Text=msg;
}