Passing data from one button click event to another button click event - c#

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);
}

Related

I have the following error when I use DropDownlist for 3rd or second time! "failed to load viewstate is being loaded must .."

I have a "listview" for showing list of employee and a "dropdownlist" to select department. The following error occurs when I use "DropDownlist" for 3rd or second time:
"Failed to load viewstate".
The control tree into which viewstate is being loaded must match the control tree that was used to save "viewstate" during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request."
This is asp.net Webform and I have to use this technology and have no other choice .
namespace .Presentation.general
{
public partial class Listg : PageBase
{
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/App_MasterPages/empty.Master";
}
protected void Page_Init(object sender, EventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateDepartmentsDropDownList();
GeneralObjectDataSource.SelectParameters["Department"].DefaultValue = "";
decimal presence = Convert.ToDecimal(Data.EmployeeDB.Create().GetCountEMPOnlineToday());
decimal visibles = Convert.ToDecimal(Data.EmployeeDB.Create().GetCountVisiblesEmployees());
visibles = (visibles == 0 ? 1 : visibles);
PresenceLabel.Text = System.Math.Round((presence / visibles) * 100, 1).ToString() + "% " + string.Format(" ({0})", presence);
}
}
public void Search(object sender, EventArgs e)
{
GeneralObjectDataSource.SelectParameters["name"].DefaultValue = Common.Converter.ConvertToFarsiYK(NameTextBox.Text.Trim());
if (PresenceRadioBottonList.SelectedValue == "1")
{
GeneralObjectDataSource.SelectParameters["onlyPresence"].DefaultValue = "true";
}
else
{
GeneralObjectDataSource.SelectParameters["onlyPresence"].DefaultValue = "false";
}
DataListView.DataBind();
}
public void select_department_SelectedIndexChanged(object sender, EventArgs e)
{
GeneralObjectDataSource.SelectParameters["name"].DefaultValue = "";
GeneralObjectDataSource.SelectParameters["Department"].DefaultValue = select_department.SelectedItem.Text;
GeneralObjectDataSource.DataBind();
DataListView.DataBind();
}
private void PopulateDepartmentsDropDownList()
{
select_department.DataSource = Biz.EmployeeBO.GetDepartments();
select_department.DataTextField = "Name";
select_department.DataValueField = "ID";
select_department.DataBind();
select_department.Items.Insert(0, new ListItem("", "0"));
select_department.SelectedValue = Biz.Settings.SelectedDepartmentID;
}
}
}

ASP.NET increase & decrease date by clicking image

I want to increase & decrease date on Image click like this. '<' for decrease and '>' for increment and show them in textbox. I tried like following code but not working
kindly help me to do so
protected void ImageButtonNextDate_Click(object sender, ImageClickEventArgs e)
{
DateTime date = DateTime.Now;
DateTime nextday = date.AddDays(1);
txtDate.Text = nextday.ToShortDateString();
}
protected void ImageButtonPrevDate_Click(object sender, ImageClickEventArgs e)
{
DateTime date = DateTime.Now;
DateTime nextday = date.AddDays(-1);
txtDate.Text = nextday.ToShortDateString();
}
Every time you handle click event on your images, you create a new date variable with value equal to current date. You need to store data between clicks somehow, so that it's retained for the next event. There are multiple ways to do so, for example, session variables:
protected void ImageButtonPrevDate_Click(object sender, ImageClickEventArgs e)
{
DateTime date = Session["MyDateVariable"] as DateTime ?? DateTime.Now;
DateTime nextday = date.AddDays(-1);
Session["MyDateVariable"] = nextday;
txtDate.Text = nextday.ToShortDateString();
}
I think you need to get the current value from the txtDate, then perform the logic.
protected void ImageButtonNextDate_Click(object sender, ImageClickEventArgs e)
{
txtDate.Text = (Convert.ToDateTime(txtDate.Text).AddDays(1)).ToShortDateString();
}
protected void ImageButtonPrevDate_Click(object sender, ImageClickEventArgs e)
{
txtDate.Text = (Convert.ToDateTime(txtDate.Text).AddDays(-1)).ToShortDateString();
}
UPDATE
You only need to load the value of DateTime.Now to txtDate on first page load, on every post back, do not set it.
if(!IsPostBack()){
txtDate.Text = DateTime.Now.ToShortDateString();
}

Displaying on different times

This is for my timer
private void timer_tick(object sender, EventArgs e)
{
string timeNow = "";
timeNow = DateTime.Now.ToString("hh:mm") + " " + DateTime.Now.ToString("tt");
medicineAlarm();
}
private void medicineAlarm()
{
DataTable dt = new DataTable();
dt = database.getSchedule();
string AMTime;
string PMTime;
string NNTime;
foreach (DataRow row in dt.Rows)
{
AMTime = row["AMIntake"].ToString();
PMTime = row["PMIntake"].ToString();
NNTime = row["NNIntake"].ToString();
if (AMTime == timeNow || PMTime == timeNow || NNTime == timeNow)
{
MessageBox.Show("Drink Medicine");
}
}
}
How can i show the message even if i am running the program? Hope you can help me. This is inside my form_load
private void Form1_Load(object sender, EventArgs e)
{
timer.Interval = 1000;
timer.Tick += new EventHandler(this.timer_tick);
timer.Start();
The medicineAlarm() method does not have any access to the timeNowvariable that you are setting up in the timer_tick() event handler. I suggest you pass the variable in:
private void timer_tick(object sender, EventArgs e)
{
string timeNow = DateTime.Now.ToString("hh:mm") + " " + DateTime.Now.ToString("tt");
medicineAlarm(timeNow);
}
private void medicineAlarm(string timeNow)
{
DataTable dt = database.getSchedule();
foreach (DataRow row in dt.Rows)
{
foreach(var label in new [] {"AM", "PM", "NN"})
if (row[label + "Intake"].ToString() == timeNow)
{
MessageBox.Show("Drink Medicine");
return;
}
}
}
I don't think your code compiles at all since the variable string timeNow = ""; is declared in event handler and doesn't exists in your method body. You may want to pass it to the method like
private void medicineAlarm(string timeNow)
{
You then call it
private void timer_tick(object sender, EventArgs e)
{
string timeNow = "";
timeNow = DateTime.Now.ToString("hh:mm") + " " + DateTime.Now.ToString("tt");
medicineAlarm(timeNow);
}

Dynamic ImageButton click event not fired

I have the following code:
protected void Page_Load(object sender, EventArgs e)
{
using (ImageButton _btnRemoveEmpleado = new ImageButton())
{
_btnRemoveEmpleado.ID = "btnOffice_1";
_btnRemoveEmpleado.CommandArgument = Guid.NewGuid().ToString();
_btnRemoveEmpleado.Height = 15;
_btnRemoveEmpleado.Width = 15;
_btnRemoveEmpleado.ImageUrl = "cross-icon.png";
_btnRemoveEmpleado.Click += new ImageClickEventHandler(_btnRemoveEmpleado_Click);
this.phPartesPersonal.Controls.Add(_btnRemoveEmpleado);
}
}
void _btnRemoveEmpleado_Click(object sender, ImageClickEventArgs e)
{
try
{
string s = "";
}
catch (Exception ex)
{
}
finally { }
}
When I click on _btnRemoveEmpleado, the postback is executed but I never reach the string s = ""; line. How could I execute the _btnRemoveEmpleado_Click code, please?
Remove the using, controls are disposed automatically by ASP.NET, they have to live until the end of the page's lifecycle. Apart from that create your dynamic control in Page_Init, then it should work.
protected void Page_Init(object sender, EventArgs e)
{
ImageButton _btnRemoveEmpleado = new ImageButton();
_btnRemoveEmpleado.ID = "btnOffice_1";
_btnRemoveEmpleado.CommandArgument = Guid.NewGuid().ToString();
_btnRemoveEmpleado.Height = 15;
_btnRemoveEmpleado.Width = 15;
_btnRemoveEmpleado.ImageUrl = "cross-icon.png";
_btnRemoveEmpleado.Click += new ImageClickEventHandler(_btnRemoveEmpleado_Click);
this.phPartesPersonal.Controls.Add(_btnRemoveEmpleado);
}

IndexOutOfRange Exception from String.Format

I want to search a file by the month of birth and display the results in label7. So what I want is to enter the number 11 into textbox5 press button4 and display all the enteries with a birthmonth of 11 into label7.text. The filename.txt is created in the first part of the program I now what to be able to search that filename.txt. Another example of what i am trying to do is. When the file was created data was entered Firstname, lastname, birthday, and birth month. I want to search that file by birth month and display the results in label7.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void tabPage2_Click(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
}
private void close_Click(object sender, EventArgs e)
{
Close();
}
private void button1_Click(object sender, EventArgs e)
{
writetext();
reset();
}
public void writetext()
{
using (TextWriter writer = File.AppendText("filename.txt"))
{
writer.WriteLine("First name, {0} Lastname, {1} Phone,{2} Day of birth,{3} Month of Birth{4}", textBox1.Text, textBox2.Text, maskedTextBox1.Text, textBox4.Text, textBox3.Text);
MessageBox.Show(String.Format("First Name,{0} Lastname, {1} Phone,{2} Day of birth,{3} Month of Birth{4}", textBox1.Text, textBox2.Text, maskedTextBox1.Text, textBox4.Text, textBox3.Text));
}
}
public void reset()
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
maskedTextBox1.Text = "";
}
private void button3_Click(object sender, EventArgs e)
{
Close();
}
private void button2_Click(object sender, EventArgs e)
{
readfile();
}
private void label7_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
string[] lines = ...
try
{
int month = Int32.parse(textBox5.Text);
label7.Text = String.Format("Month of Birth {0}", lines[month]);
}
catch(Exception e){
label7.Text = "Invalid input";
}
}
public void readfile()
{
string[] lines = File.ReadAllLines("filename.txt");
label6.Text = String.Join(Environment.NewLine, lines);
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
}
}
}
Instead
label7.Text = (String.Format("Month of Birth{4}", textBox5.Text));
Use
label7.Text = (String.Format("Month of Birth{0}", textBox5.Text));
The {0} 0 in curly brace means the 0-positioned argument in String.Format argument list, in this case, refers to textBox5.Text
--Update--
Seems you need to print the [month]-th line of the text file to Label7, the code should be:
string[] lines = ...
try{
int month = Int32.parse(textBox5.Text);
label7.Text = String.Format("Month of Birth {0}", lines[month]);
}
catch(Exception e){
label7.Text = "Invalid input";
}
Judging by your comment on xandy's answer, it is impossible for us to help you without knowing the file format of filename.txt. However, you probably want something like this.
private void button4_Click(object sender, EventArgs e)
{
string[] lines = File.ReadAllLines("filename.txt");
string result = GetResultFromLines(lines, textBox5.Text);
label7.Text = (String.Format("Month of Birth{0}", result));
}
You will have to write the GetResultFromLines function yourself, based on how you want to retrieve your data from file.
The number in brackets is not the field width - it's the index of the parameter to use.

Categories