I currently have a form class that handles combo boxes called "Settings". In the combo box are a list of seconds to select, ie. 30 Seconds, 60 Seconds. This seems really simple but I can't get my head around it!
I currently have this in the Settings class where the combo boxes are used
private void timeSelect_SelectedIndexChanged(object sender, EventArgs e)
{
timeSelected = this.timeSelect.GetItemText(this.timeSelect.SelectedItem);
if (timeSelected == "120 Seconds")
seconds = 120;
}
The variable seconds being a public int in that class. In a different class called Time, I want to be able to access this integer so I can set the timer value to whatever has been selected. I tried making a method in Time that takes in the int, called it in the Settings class so it saves the value into a variable in the Time class. Something like this:
In the Time class:
public int j;
public void timeChosen(int secondsChosen)
{
j = secondsChosen;
}
and called the method above in the Settings class to pass the value "seconds"
However, this doesn't work and when application starts the value of j as 0. But when it's first called, it does take into account that the value might be 120 but it does not seem to save the value.
Any suggestions?
In Settings class:
Time time = new Time();
public int seconds;
public string timeSelected;
private void timeSelect_SelectedIndexChanged(object sender, EventArgs e)
{
timeSelected = this.timeSelect.GetItemText(this.timeSelect.SelectedItem);
if (timeSelected == "120 Seconds")
seconds = 120;
}
private void nextButton_Click(object sender, EventArgs e)
{
time.timeChosen(seconds);
this.Hide();
var nextForm = new NextForm();
nextForm.ShowDialog();
}
In Time class:
public int j;
public void timeChosen(int secondsChosen)
{
j = secondsChosen;
}
The timer is set up in a different class but that all works fine, it's just a matter of passing and saving the value from the combo box. As in the Time class I can just set it to public int j = 60; and it sees it as 60 seconds and works.
I suggest to use standard application settings.
You need to create a setting file and add a new variable in the settings
Right click on a project in the solution explorer
Go to Properties -> Settings Tab and create a new setting file
Then create a new int variable Seconds in the grid view on the
same page.
So after, you will be able to get/set this setting variable using Properties.Settings.Default.Seconds
private void nextButton_Click(object sender, EventArgs e)
{
Properties.Settings.Default.Seconds = seconds;
this.Hide();
var nextForm = new NextForm();
nextForm.ShowDialog();
}
Related
i'm currently having a problem getting value from another tab page in windows form using c#. I have tabPage1 and tabPage 2 inside tabControl. I want to use the value I have saved in tabpage1 for another calculation in tabPage 2 but I can't find a way to do this. Here is an example of what i want for further understanding my question. Please anyone help me fix this, thank you.
private void button1_Click_1(object sender, EventArgs e)
{
double age = Convert.ToDouble(richTextBox1.Text);
}
private void button2_Click(object sender, EventArgs e)
{ double a=0;
for (int i=1,i<age,i++)
{
a=a+i;
}
}
P.s. button1 is in tabPage1 and button2 is in tabPage 2
This is an issue with variable scoping. In your button2_Click method you are probably getting an error about age not being declared.
There are a few options:
Get the value of age in your button2_Click method again.
private void button2_Click(object sender, EventArgs e)
{
double a = 0;
double age = Convert.ToDouble(richTextBox1.Text); // Get value again locally.
for (int i = 1; i < age; i++)
{
a += 1;
}
}
This will mean that age is available within the scope of button2_Click.
Store it in a property on the form, making it available to all your methods in that Form.
public partial class Form1 : Form
{
private int Age { get; set; } // Property that stores age in the class.
private void button1_Click_1(object sender, EventArgs e)
{
Age = Convert.ToDouble(richTextBox1.Text); // Store in property not local var
}
private void button2_Click(object sender, EventArgs e)
{
double a = 0;
for (int i = 1; i < Age; i++) // Loop to property value not local var.
{
a += 1;
}
}
}
Which option you choose will depend on your use case (e.g. if pressing button 1 is necessary before pressing button 2, then you will want to go with option 2; but if you could just press button 2 without first pressing button 1 then option 1 would work).
Please note that, in your for loop you have used commas, where you need to use semicolons, my example above correct this.
In addition, as #LarsTech has mentioned, you need to use int.TryParse ideally, as the value in your textbox may not be a number.
I need to make a form in C# have a timer and have a label that will have be the display of the timer. The label will need to be a generic label at first saying it is a counter, but when the timer starts it needs to display the count. Currently I have the display as a number up down but, it needs to be the control that can tweak the count, which it does. It just can't be the sole counter.
Here is my assignment:
Create a Windows Application. In the main form, create a label named “lTickCount”.
Create a timer named “tPeriodic”, and a numerical control of your own choosing.
Each time the timer “ticks” increment an integer, display the integer value as a string in
lTickCount. Use the numerical control to change the update rate of the timer
interactively.
I think I have done everything correctly except for the bold part. To finish I tried to make a string in both the label and the counter. I know I shouldn't have in both, I just wanted to show you the two things I've tried to help get better feedback:
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Text = "AAAAAAAA AAAAAAAA ########";
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
TickCounter.Text = "The timer has started";
tPeriodic.Enabled = true;
}
else
{
TickCounter.Text = "The timer has ended";
tPeriodic.Enabled = false;
}
}
private void TickCounter_ValueChanged(object sender, EventArgs e)
{
TickCounter.Text = TickCounter.Value.ToString();
}
private void tPeriodic_Tick(object sender, EventArgs e)
{
TickCounter.Value += 1;
}
private void label1_Click(object sender, EventArgs e)
{
TickCounter.Text = TickCounter.Value.ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Can someone help me figure out what I'm doing wrong and point me in the right way?
If you are going to try to add to a string (A label value) you need to convert it to an Integer first.
A couple ways to do this:
TextCount.Text = (Convert.ToInt32(TextCount.Text) + 1).ToString();
is one way, of course you could still use your += or any other math syntax for basic addition of +1.
You can also use tryParse, and in fact this should probably be used to verify you have an integer in the first place:
int count;
if (int.TryParse(TextCount.Text, out count))
{
count++;
TextCount.Text = count.ToString();
}
int count;
int tmrInterval = 1000; //1 sec
private void tPeriodic_Tick(object sender, EventArgs e)
{
count++;
lTickCount.Text = count.ToString();
}
private void TickCounter_ValueChanged(object sender, EventArgs e)
{
if (TickCounter.Value == 0)
{
return; // or stop the timer
}
tPeriodic.Interval = TickCounter.Value * tmrInterval;
}
tPeriodic.Interval is the time till next tick in milliseconds.
You are updating the timer interval according to tmrInterval and the value of the numeric control. You can change the interval or the formula i wrote to your own.
valter
Ok I found that:
tPeriodic.Interval = 1000 / Convert.ToInt32(TickCounter.Value * TickCounter.Value);
seemed to work in the numericupdown class.
Thanks for the help.
And dammit, I'm getting frustrated. I'm doing my first mini-game, I think the name in english is Tic-Tac-Toe, and so, I have a main menu where I choose the option 2 players, then i get a inputbox asking for the 2 players names (i used a visual basic reference) and store it in 2 variables that i send to my constructor (?). I'm potuguese so I don't really know how you guys call it, but I'll show you the code.
So, in the first Form, I have:
private void doisJogadoresToolStripMenuItem_Click(object sender, EventArgs e)
{
jogadorTempUm = Microsoft.VisualBasic.Interaction.InputBox("Jogador 1");
jogadorTempDois = Microsoft.VisualBasic.Interaction.InputBox("Jogador 2");
jog = new DoisJogadores(jogadorTempUm, jogadorTempDois);
DoisJogadores novoDois = new DoisJogadores();
novoDois.ShowDialog();
}
That gets sent to the other Form:
public DoisJogadores(string teste1, string teste2)
{
jogador1 = teste1;
jogador2 = teste2;
}
And I save it in the class:
private string jogador1
private string jogador2
And the values get saved there. But I tried to place them in a textbox to show the players names and it just goes blank.
Anyone that can help me?
You are showing not that form which you are passing values to. Here is a fix
private void doisJogadoresToolStripMenuItem_Click(object sender, EventArgs e)
{
jogadorTempUm = Microsoft.VisualBasic.Interaction.InputBox("Jogador 1");
jogadorTempDois = Microsoft.VisualBasic.Interaction.InputBox("Jogador 2");
// pass values to form you are creating
DoisJogadores novoDois =
new DoisJogadores(jogadorTempUm, jogadorTempDois);
novoDois.ShowDialog();
}
Also make sure you are assigning jogador1 and jogador2 to textboxes. E.g. you can subscribe to form's load event in DoisJogadores form:
private void DoisJogadores_Load(object sender, EventArgs e)
{
textbox1.Text = jogador1;
textbox2.Text = jogador2;
}
I am new to C#, and I have searched I but didn't find a simple solution to my problem.
I am creating a Windows form application.
After the start button is clicked, it counts every millisecond and when it reaches specific values from an array changes a label.
How can milliseconds be counted?
-------------------------
AlekZanDer Code:
namespace timer_simple3
{
public partial class Form1 : Form
{
long result = 0;
public Form1()
{
InitializeComponent();
this.timer1 = new System.Windows.Forms.Timer(this.components);
}
private void Form1_Load(object sender, EventArgs e)
{
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
}
private void timer1_Tick(object sender, EventArgs e)
{
result = result + 1;
label1.Text = Convert.ToString(result);
}
private void btstart_Click(object sender, EventArgs e)
{
timer1.Interval = 1; //you can also set this in the
//properties tab
timer1.Enabled = true;
timer1.Start();
// label1.Text = Convert.ToString(timer1);
}
private void btstop_Click(object sender, EventArgs e)
{
timer1.Stop();
}
}
}
How can milliseconds be counted?
You can't do that, because Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds. If you require a multithreaded timer with greater accuracy, use the Timer class in the System.Timers namespace.
Also any other timer will not give you accuracy more than 16 milliseconds (actually 15.625 milliseconds, or 64Hz). So, you can't increment some counter to count elapsed milliseconds.
Option for you - instead of long result counter use difference between current time and time of timer start:
label1.Text = (DateTime.Now - startDateTime).Milliseconds.ToString();
First you have to create a method that tells the timer what to do every [put the needed number here] milliseconds.
private void randomTimer_Tick(object sender, EventArgs e)
{
if (conditions)
{
... //stuff to do
... //more stuff to do
... //even more stuff to do
}
}
Then you set the timer to call this method: you can do this by using the events tab of the properties of the timer or write:
this.randomTimer1.Tick += new System.EventHandler(this.randomTimer1_Tick);
in the ProjectName.Designer.cs file in the private void InitializeComponent(){} method after the line this.randomTimer = new System.Windows.Forms.Timer(this.components);.
And lastly you enable the timer:
private void startButton (object sender, EventArgs e)
{
randomTimer.Interval = timeInMilliseconds; //you can also set this in the
//properties tab
randomTimer.Enabled = true;
}
Of course, you will have to set the button to call this method too.
If you don't know where the Properties window is (I assume that you are using Visual C#): it's usually a tab located on the right side of the window. In order something to appear in the tab, you have to select the form you want to edit in the design view. If there is no such tab anywhere in the window of the compiler, go to "View" -> "Other Windows" and select "Properties Window".
If the answers you have found are long and complicated, that's mostly because they are explaining the whole process with details and examples. If you use the "drag and drop" option of Visual C#, the declaration code of the forms will happen automatically, afterwards it's up to you to write the code of the methods. There are also other features that are self explanatory and make programming more pleasant. Use them!
In Visual studios, is the class recalled every time the page refreshes? I have the following class - I want to add value to a variable every time a button is clicked;
public partial class _Default : System.Web.UI.Page
{
Random random = new Random();
int total;
int playerTotalValue;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ranPlayer_Click(object sender, EventArgs e)
{
int randomNumTwo = random.Next(1, 10);
playerTotalValue = playerTotalValue + randomNumTwo; //playerTotalValue gets reset to zero on every click
playerTotal.Text = playerTotalValue.ToString();
}
}
playerTotalValue gets resets to zero every time I click 'ranPlayer' button, or this is what I think happens.
HTTP is stateless. That means it will not retain the values in the variable like you do in windows form programming. So whenever you click on the button it executes the same way as it loaded in the initial page loading. But wait !. You have the value available in the text box. So you can read the value from there and store it in the variable.
protected void ranPlayer_Click(object sender, EventArgs e)
{
playerTotalValue =0;
if(!String.IsNullOrEmpty(playerTotal.Text))
{
playerTotalValue =Convert.ToInt32(playerTotal.Text);
}
int randomNumTwo = random.Next(1, 10);
playerTotalValue = playerTotalValue + randomNumTwo; //playerTotalValue gets reset to zero on every click
playerTotal.Text = playerTotalValue.ToString();
}
The duration of this instance is the request. After that it is discarded. Every request will use separate objects.
Any state you need to preserve between requests must be either part of the request (for example an http form field or cookie), or held at the server (session-state).
So yes: playerTotalValue is 0 at the start of each request.
I would create a property that will be storing the value in a ViewState so the value will be preserved on postbacks.