How can I change a labels text on a certain time - c#

The label must change when the page loads. I don't get any errors but the label stays what I named the label.
my code:
private void Form1_Load(object sender, EventArgs e)
{
DateTime curTime = DateTime.Now;
int one = 5; //times of day
int two = 12;
int three = 20;
string ogg = "Oggend";
string mid = "Middag";
string aan = "Aand";
if (curTime.Hour >= one && curTime.Hour <= two)
{
timelbl.Text = ogg;
}
else if (curTime.Hour > two && curTime.Hour < three)
{
timelbl.Text = mid;
}
else
{
timelbl.Text = aan;
}
}
I tried to put timelbl.Text = "Oggend" in aswell but it didn't work.
Oggend means Morning, Middag means Day and aand means Night

Using variables for "times of day" is redundant. You may keep them if that's what you want, but it won't be the best thing to do.
private void Form1_Load(object sender, EventArgs e) {
DateTime curTime = DateTime.Now;
int one = 5; //times of day
int two = 12;
int three = 8;
string ogg = "Oggend";
string mid = "Middag";
string aan = "Aand";
if (curTime.Hour >= one && curTime.Hour <= two)
{
timelbl.Text = ogg;
}
else if (curTime.Hour > two && curTime.Hour < three)
{
timelbl.Text = mid;
}
else
{
timelbl.Text = aan;
}
}

Your code seems to be fine. You just need to make sure that page load event fires so that the variable value assigned to the label. You should add a break point in page load event and ensure that the event fires properly.

Related

Why looping twice on string length test

I'm working in C# (2013) Windows Forms. My instructor wanted us to ensure that the txtStateInput is upperCase when we hit the calculate button. However when I input a two character string such as "wi" and then hit calculate, it throws the message "enter valid state" and clears out the textbox. When I enter the "wi" in a second time then it works. I can't figure out why this is happening, the code would lead me to believe that it would check to ensure the string in txtStateInput is two characters and then when calculate is clicked it would uppercase the string. I can't figure out why it only works once I enter in the state "wi" a second time.
private void btnCalc_Click(object sender, EventArgs e)
{
//declare variables.
int startPop = 0;
int endPop = 0;
string Message = "Error";
decimal Percent = 0.0m;
string State = "";
string City = String.Empty;
int dTimes = 0;
try
{
City = txtCityInput.Text;
//System Globalization was initialized so this method works.
TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
txtCityInput.Text = myTI.ToTitleCase(City);
if(txtStateInput.Text.Length != 2)
{
MessageBox.Show("Enter valid State");
txtStateInput.Focus();
txtStateInput.SelectAll();
}
else
{
State = txtStateInput.Text.ToUpper();
txtStateInput.Text = State;
if ((int.TryParse(txtStartPopInput.Text, out startPop)) && int.TryParse(txtEndPopInput.Text, out endPop))
{
if ((startPop > 0) && (endPop > 0))
{
//if population has decreased.
if ((startPop > endPop))
{
Percent = ((decimal.Parse(endPop.ToString()) - decimal.Parse(startPop.ToString())) / decimal.Parse(startPop.ToString()));
Message = "Pop. Decrease of " + Percent.ToString("p");
}
//if population has increased.
if ((startPop < endPop))
{
Percent = ((decimal.Parse(endPop.ToString()) - decimal.Parse(startPop.ToString())) / decimal.Parse(startPop.ToString()));
Message = "Pop. Increase of " + Percent.ToString("p");
}
//if population has not changed.
if ((startPop == endPop))
{
Percent = ((decimal.Parse(endPop.ToString()) - decimal.Parse(startPop.ToString())) / decimal.Parse(startPop.ToString()));
Message = "No Change in Population";
}
}
else
{
MessageBox.Show("Please enter valid population figures.");
}
}
if (int.TryParse(txtDisplayTimes.Text, out dTimes))
{
if (dTimes > 0)
{
lstResults.Items.Clear();
int iSum = 0;
int iLoopCount = dTimes;
//displays the results according to value in txtDisplayTimes.
for (iSum = 1; iSum <= iLoopCount; iSum++)
{
lstResults.Items.Add(Message);
}
}
}
}
}
catch
{
MessageBox.Show("Something went wrong.");
}
}

Retrieve products properties of specified date

I'm reading a file that is looking like that with a lot of strings
PrId Name Quantity Price Date
3 Milk 2 100 23-08-15
I have a button - btnDat_Click. When i click it retrieves all the dates in a listbox named listDate. I create a button named btnDataToTb_Click, i need to select the date and when i click the button it gonna show properties(Id, Name,Quantity) of all products of that date.
PrId Name Quantity Price
3 Milk 2 100
That's the whole code
char[] cc = new char[500]; int i, nr;
string[] lines = new string[250];
public void btnRead_Click(object sender, EventArgs e)
{
string FileName = textBox1.Text;
FileStream r_stream = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite);
StreamReader reads_string_from_r_stream = new StreamReader(r_stream);
i = 0;
listBox1.Items.Clear();
listBox2.Items.Clear();
for (; ; i++)
{
textBox1.Text = reads_string_from_r_stream.ReadLine();
lines[i] = textBox1.Text;
listBox1.Items.Add(lines[i]);
listBox2.Items.Add(lines[i]);
if (reads_string_from_r_stream.EndOfStream.Equals(true)) goto nn;
}
nn:
textBox2.Text = reads_string_from_r_stream.EndOfStream.ToString();
r_stream.Close();
nr = listBox1.Items.Count;
textBox6.Text = nr.ToString();
}
private void SelectPath_Click(object sender, EventArgs e)
{
OpenFileDialog openFile1 = new OpenFileDialog();
openFile1.Filter = "Text Files|*.txt";
if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
textBox1.Text = openFile1.FileName;
}
public void button1_Click(object sender, EventArgs e)
{
int n = Convert.ToInt16(textBox6.Text);
ListB.Items.Clear();
for (i = 0; i < n; i++)
{
ListB.Items.Add(lines[i]);
}
}
private void btnDat_Click(object sender, EventArgs e)
{
int n = Convert.ToInt16(textBox6.Text);
for (i = 0; i < n; i++)
{
if(! listDate.Items.Contains(lines[i].Split('\t')[lines[i].Split('\t').Length - 1]))
{
listDate.Items.Add(lines[i].Split('\t')[lines[i].Split('\t').Length - 1]);
}
}
listData.Items.RemoveAt(0);
}
private void btnDataToTb_Click(object sender, EventArgs e)
{
if (listData.SelectedItems.Count > 0)
{
string data = listData.SelectedItem.ToString();
string[] date = data.Split('-');
int day = Convert.ToInt32(date[0]);
int month = Convert.ToInt32(date[1]);
int year = Convert.ToInt32(date[2]);
DateTime a = new DateTime(year, month, day);
for (i = 0; i < listBox2.Items.Count; i++)
{
DateTime data2 = DateTime.Parse(lines[i].Split('\t')[lines[i].Split('\t').Length - 1]);
int result = DateTime.Compare(a, data2);
if(result == 0)
listBox3.Items.Add(string.Format("{0}\t{1}\t{2}\t{3}", lines[i].Split('\t')[0], lines[i].Split('\t')[1], lines[i].Split('\t')[2], lines[i].Split('\t')[3]));
}
}
else
{
MessageBox.Show("Select a date");
}
}
I'd say you're approaching this problem wrong. Instead of reading the data, storing them in a list box, then reading and parsing them again when you need to, which is really complicated, you should rather do this:
Create a new class (e.g. Item) that has properties for the product id, name, quantity, price, and date.
When reading the data, parse the lines immediately and create a new instance of said class for each line. Store these in a List<Item>.
When working with FileStream, StreamReader etc (anything that implements IDisposable/has a Dispose() method) you should use them in a using block (like using (StreamReader sr = …) { /* work with sr here */ }); this will automatically free the object after use.
For making data visible to the GUI, you can either use data binding, or fill the listbox by hand and get the selected item with SelectedIndex.
Use Linq for querying data. To select all items on a specific date you can use var onThisDate = itemList.Where(item => item.Date == selectedDate). Linq has many more functions for selecting, filtering and projecting data.

So the first if statement never triggers because it does not seem to read the negative number entered in the text box

private void button1_Click(object sender, EventArgs e)
{
double temp = double.Parse(textBox1.Text);
if (temp < 0)
{
label2.Text = "Freezing.";
}
if (temp > 40)
{
label2.Text = "Hot.";
}
else
{
label2.Text = "Moderate.";
}
}
Whenever converting user input, or any form of type String in to an object, I always like to use TryParse(...) as it provides you with better control if something isn't right.
double temp = 0.0d;
var converted = double.TryParse(textBox1.Text, out temp);
if (!converted) throw new Exception("Please enter a positive or negative temperature.");
if (temp < 0.0d)
{
// Freezing
}
else if (temp >= 0.0d && temp < 40.0d)
{
// Moderate
}
else if (temp >= 40.0d)
{
// Hot
}
The key is finding out what the value is being read in to temp. If its bringing in a negative number then I would recommend the code change below. What its really doing is if the 1st isnt true, then it checks the second, and finally it uses the third if neither are true.
private void button1_Click(object sender, EventArgs e)
{
double temp = double.Parse(textBox1.Text);
if (temp < 0)
{
label2.Text = "Freezing.";
}
else if (temp > 40)
{
label2.Text = "Hot.";
}
else
{
label2.Text = "Moderate.";
}
}

How to get header values when click pivot table item in a gridview

This could be a little tricky so please bear with me.
I have this result from a gridview, the data came from a pivot table:
DateCreate 02/11/2013 02/19/2013 Total
OrdersPendInvoice 0 1 1
OrdersPendPickUp 1 15 16
Here the selectable items are the numbers, and just the numbers greater than zero.
So first I need for those items (the selectable ones) make them like linkButtons son when I click in one of them I can pass as reference (here the other tricky part) both headers.
Let's put an example:
If I clicked on number 15, which basically means that there are 15 OrdersPendPickUp for the date 02/19/2013. Then I will go to a different page with the references 02/19/2013 and OrdersPendPickUp and there show those 15 records. I have no problem with the last part as long as I have the references.
And for the Total case, I'd just need either the OrdersPendInvoice or OrdersPendPickUp (depending on the item selected) cause I will get all records for that reference no matter the date.
I did this but it's not much really, just changes the color of the items greater than zero :(
protected void gvOrdersProcessed_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Pager)
{
for (int i = 0; i <= e.Row.Cells.Count - 1; i++)
{
if (TryToParse(e.Row.Cells[i].Text) > 0)
{
e.Row.Cells[i].ForeColor = System.Drawing.Color.Red;
}
}
}
}
private int TryToParse(string value)
{
int number;
bool result = Int32.TryParse(value, out number);
if (result)
return number;
else
return 0;
}
Yes, it is tricky. However, give the following a try:
private List<string> _headers = new List<string>();
protected void gvOrdersProcessed_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Collect the texts from the column headers
if (e.Row.RowType == DataControlRowType.Header)
{
for (int i = 0; i <= e.Row.Cells.Count - 1; i++)
{
this._headers.Add(e.Row.Cells[i].Text);
}
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i <= e.Row.Cells.Count - 1; i++)
{
if (TryToParse(e.Row.Cells[i].Text) > 0)
{
string rowKey = e.Row.Cells[0].Text;
string column = this._headers[i];
HyperLink link = new HyperLink();
link.Text = e.Row.Cells[i].Text;
link.NavigateUrl="page.aspx?key=" + rowKey + "&column=" +column;
e.Row.Cells[i].Controls.Clear();
e.Row.Cells[i].Controls.Add(link);
}
}
}
}
Links would be like:
Normal values: ~/page.aspx?key=OrdersPendPickUp&column=02/19/2013
Total: ~/page.aspx?key=OrdersPendPickUp&column=Total

Getting integer from textbox

I want to write the event handler method button1_Click to calculate whether student’s Grade is “PASS” or “FAIL”. The student passes the course if the total score is greater than or equal to 50. The total score is Midterm(textbox1) + Final(textbox2) scores. However, teacher can give student Extra Credit(checkbox1) which is worth 10 points. The result will present in the textBox3
Here's my code:
private void button1_Click(object sender, EventArgs e)
{
int midtermInt = int.Parse(textBox1.Text);
int finalInt = int.Parse(textBox2.Text);
if (checkBox1.Checked)
{
if ((midtermInt + finalInt) + 10 >= 50)
{
grade.Text = "PASS";
}
else if ((midtermInt + finalInt) + 10 < 50)
{
grade.Text = "FAIL";
}
}
else if (!checkBox1.Checked)
{
if ((midtermInt + finalInt) >= 50)
{
grade.Text = "PASS";
}
else if ((midtermInt + finalInt) < 50)
{
grade.Text = "FAIL";
}
}
When I run it, it says "Inut string was not in a correct format.. :(
I'm very new to C# please advise me if my code is wrong anywhere
The input will only be integers never texts..
You should use int.TryParse insted int.Parse, it's check is specified string is in correct format.
You code may looks like this:
int midtermInt;
if (!int.TryParse(textBox1.Text, out midtermInt))
{
labelError.Text = "Icorrect value in field 'textBox1'".
return;
}
If you type non-numeric characters in your textbox and try to parse the text, it will throw you this exception. Try trimming the input and definitely consider adding UI validation to your forms.
You can add checking, if text in text box is in correct format in TextChanged event:
private void textBox_TextChanged(object sender, EventArgs e)
{
int val;
if (textBox.Text.Length == 0 || !int.TryParse(textBox.Text, out val))
tsPassingScore.Text = "0";
}
And in your click you can check if there is number in textBox again with int.TryParse
Also you can improve your code:
If final summ is not bigger then 50 - it is automatically smaller! And it would be more readable, if you introduce extra variable - for teachers extra credit:
int extraCredit = checkBox1.Checked ? 10 : 0;
int finalScore = midtermInt + finalInt + extraCredit;
if (finalScore >= 50)
grade.Text = "PASS";
else
grade.Text = "FAIL";

Categories