Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Very new to C# and programming in general. I've run into this problem and I don't really know how to solve it. First of all, here's the code :
It says in the "if" parts of the code that random1 does not exist in the current context. Yes, I am aware that random only exists within the Button_click part because it is between brackets. The code is supposed to pick a random number between 0 and 20 without displaying it so that the user has to guess it. If the user is wrong, it shows a hint saying if the number is too high or too low. How can I fix this problem? Thanks
EDIT : It seems that I was too vague, your answers were good though. This is the full code :
public void Button_Click(object sender, RoutedEventArgs e) //random
{
Random chiffrealeatoire = new Random();
int random1 = (chiffrealeatoire.Next(0, 20));
}
private void Button_Click_1(object sender, RoutedEventArgs e) //quit
{
Application.Current.Shutdown();
}
private void Button_Click_2(object sender, RoutedEventArgs e) //veri
{
}
public void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (BoiteChiffre.Text < random1)
{
MessageBox.Show("Too low");
}
if (BoiteChiffre.Text > random1)
{
MessageBox.Show("Too high");
}
else
{
MessageBox.Show("Congratulations");
}
}
The user is supposed to write in the textbox
You've closed off your method and left out the if statement! The random1 variable is defined and declared within your method so it doesn't exist outside of it. Please move the method's closing bracket to include the if statement as well.
Also, your two if statements should really be linked together with an else if. You've declared two separate if statements so only one of them will have the else. Not wrong, just better practice to the following.
Basic structure:
public void Button_Click(object sender, RoutedEventArgs e) {
...
int random1
if(<random1) {
random1
} else if(>random1) {
...
} else {
...
}
} // <- method closing bracket
Edit: Since you've heavily modified the code provided I'll have to update my explanation.
Your issue has to do with variable scope. A variable defined within a method has local scope to that method. It's not accessible and doesn't even exist outside of it. You should be declaring your method OUTSIDE all the methods so that you can have multiple methods using it.
Basic structure:
int random1
public void methodA() {
random1 = whatever
}
public void methodB() {
if(random1) {
...
}
}
Please try the below code snippet. You need to declare the variable inside of the same method.
public void Button_Click(object sender, RoutedEventArgs e) //random
{
Random chiffrealeatoire = new Random();
int random1 = (chiffrealeatoire.Next(0, 20));
if (BoiteChiffre.Text < random1)
{
MessageBox.Show("Too low");
}
if (BoiteChiffre.Text > random1)
{
MessageBox.Show("Too high");
}
else
{
MessageBox.Show("Congratulations");
}
}
Related
I've been creating a autocheckout bot, and I'm very new to C#, and coding in general. I've gotten pretty far, almost done with the program, or so I thought, and now I want to have the ability to create multiple tasks, or run the task method multiple times. I also want to be able to input a different "profile", which has defined strings, such as login email, password, ect., on each task seperately. I'm very stuck and I have no idea where to even begin, maybe if someone could point me in the right direction for me to get started? last time I got some amazing help from this community, and it helped me a lot. Here is my current attempt:
public void KeywordTask1()
{
Start();
LogIn();
FindProductByKeyword();
stopwatch.Start();
AddToCart();
Checkout();
TimeSpan CheckoutTime = stopwatch.Elapsed;
}
public void KeywordTask2()
{
Start();
LogIn();
FindProductByKeyword();
stopwatch.Start();
AddToCart();
Checkout();
TimeSpan CheckoutTime = stopwatch.Elapsed;
}
I have buttons that start those tasks, but I also want the varibles to change, like a status text that I have set in my windows form. here is my GUI if it helps you understand my code a bit better:
https://gyazo.com/c6e9334e04aeb223e0afade6da8bec4e
Please let me know if you need anything else from me! I'm not sure if this is allowed but I'm willing to pay for someone to help me through this, not very much because I'm only 16 haha, but anyway, Thank you!
Well, I am not sure if this is what you want but if you want to run method with different variable value then create method:
public void MyMethod(string myVariable)
{
//do something with myVariable
}
And you can pass different variable value when calling method:
MyMethod("123abc");
or something like:
var newVariable="123abc"
MyMethod(newVariable);
To start method with different input create method with variable
public void MyUsername(string username)
{
MessageBox.Show(username);
}
private void buttonUsername1_Click(object sender, EventArgs e)
{
MyUsername("Adam");
}
private void buttonUsername2_Click(object sender, EventArgs e)
{
MyUsername("Jack");
}
To start method multiple time use loop
private void btnDoAllTask_Click(object sender, EventArgs e)
{
int count = 0;
// run 5 times
while(count < 5)
{
count++;
MyUsername("username" + count.ToString());
}
}
or loop through array
private void btnDoAllTask_Click(object sender, EventArgs e)
{
var listUsername = new string[] { "one", "two", "three" };
foreach (var username in listUsername)
{
MyUsername(username);
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I've searched this question here before asking and all of the answers seem to be people putting code after return break or others. I am having an issue where no matter what I put in an if statement, the code reads that it is unreachable.
private const double quarterPrice = 4.50;
private const double halfPrice = 7.50;
private const double fullPrice = 10.00;
private const double taxRate = .08;
private int orders = 0;
private double sales = 0;
private void btnFindMax_Click(object sender, EventArgs e)
{
if (quarterPrice > halfPrice)//if i put something in here, it is unreachable
{
int i = 1;//unreachable
if (quarterPrice > fullPrice)//unreachable
{
}
}
}
This is frustrating because I have nor idea why it's wrong, or what to do to fix it. It doesn't give me the red error underline, only the green suggestion line. However, when compiled, none of the code inside of the if statement executes.
I even tried to do:
private void btnFindMax_Click(object sender, EventArgs e)
{
if (quarterPrice < halfPrice)
{
Close();
}
}
And the code still didn't execute. I have no idea what is going on..
You have defined the variables as constants. The compiler knows that the condition in your if statement will never be true.
You have defined quarterPrice and halfPrice as constants. The compiler knows that quarterPrice will never be greater than halfPrice and is providing you with a warning.
For example you can generate the same warning like this.
if (false)
{
int i = 1;
// Do other work.
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I am trying to learn programming and I am starting with a book called Software Development Fundamentals. However I am having loads of difficulty understanding certain subjects. Especially because my native language is not English. I am stuck at the subject (events) and (delegates). I feel like this is to difficult for me, I can not even get this code to work!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lesson02
{
class Program
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Changed += new EventHandler(r_Changed);
r.Length = 10;
}
static void r_changed(object sender, EventArgs e)
{
Rectangle r = (Rectangle)sender;
Console.WriteLine(
"Value Changed: Length = {0}",
r.Length);
}
}
class Rectangle
{
public EventHandler Changed;
private double length;
public double Length
{
get
{
return length;
}
set
{
length = value;
Changed(this, EventArgs.Empty);
}
}
}
}
I get this error:
Error 1 The name 'r_Changed' does not exist in the current context 14 59 Lesson02
C# is case-sensitive language. You have defined function as r_changed and using it as r_Changed
Use
r.Changed += new EventHandler(r_changed);
instead of
r.Changed += new EventHandler(r_Changed);
I'm pretty sure you'd know by now that C# is a case sensitive programming language.
This should work
static void r_Changed(object sender, EventArgs e)
{
Rectangle r = (Rectangle)sender;
Console.WriteLine("Value Changed: Length = {0}", r.Length);
}
Notice how r_Changed is capitals (r_changed is what you originally defined)
I would suggest using this because it is easier to read.
There is a little typo mistake in your code. It should be r_Changed instead of r_changed in the your Event Handler.
i.e write
static void r_Changed(object sender, EventArgs e)
in place of
static void r_changed(object sender, EventArgs e)
(Remember C# is Case-sensitive)
I'm very new to C#, passing arguments, modularizing and value-returning methods are pretty tought for me.
I'm trying to get two buttons to interact with each other.
One button has a counter on it. Each time it is clicked a variable that has started out with 1 gets added another one.
And the other button displays the number that the counter on the other button is on.
I hope this makes sense.
private void button_Click(object sender, EventArgs e)
{
}
private int TotalCount(int count)
{
return count += 1;
}
private void buttonCount_Click(object sender, EventArgs e)
{
int totalcount;
int count;
totalcount = TotalCount(ref count);
MessageBox.Show("The number clicked is: " + totalcount);
}
You'll need to make 'count' an instance variable...
int count = 0;
private void button_Click(object sender, EventArgs e)
{
}
private int TotalCount()
{
++count;
return count;
}
private void buttonCount_Click(object sender, EventArgs e)
{
int totalcount = TotalCount();
MessageBox.Show("The number clicked is: " + totalcount);
}
You were declaring 'count' as a local variable, so it was being initialized on each entry to the method, thus the value was not persistent. Reference arguments are not needed in this case, so they have been removed.
As Garry Vass points out reference arguments are not needed in this case however if you are using reference arguments both the definition and the calling of the method needs to specify ref
private int TotalCount(ref int count)
{
return count += 1;
}
Here is a reference that explains the ref keyword more completely.
http://msdn.microsoft.com/en-us/library/14akc2c7.aspx
Although Gary Vass is correct that count needs to be an instance variable, I wouldn't consider his answer as the right way to go about coding it.
Method names are critically important, especially as a code base grows, and you should follow the principle of "least astonishment". In this case the name of a method should indicate what it will do and it shouldn't have hidden side effects. See http://www.atalasoft.com/cs/blogs/stevehawley/archive/2006/02/27/9590.aspx
The name TotalCount implies that it will return the total count. Nothing about that name indicates that it is actually going to modify data.
The route I would take is:
int count = 0;
private int IncrementCount() {
count++;
return count;
}
private void buttonCount_Click(object sender, EventArgs e)
{
int totalcount = IncrementCount();
MessageBox.Show("The number clicked is: " + totalcount);
}
The difference is subtle. However, someone glancing through just the buttonCount_Click method would have a pretty good idea what IncrementCount() does without actually having to investigate that code.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i'm new to winform and i can't figure out how to use the BackgroundWorker.
basically what i'm trying to do is this:
i have 1 form with 2 buttons: "Import" and "Exit" . when calling ImporButton_Click all it does is creates an HttpListener and listen to a given URL. ExitButton_Click closes the form.
the problem is when i press "Import" the form get stuck and it's in "not responding" status until someone is calling the listener and free it.
i'm trying to under stand how BackgroundWorker can help me to overcome that "stuck" problem. i don't understand how to invoke the backgroundWorker1_DoWork method
Here is my code so far:
//Program.cs
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new ConfigurationForm());
}
}
//ConfigurationForm.cs
public partial class ConfigurationForm : Form
{
public ConfigurationForm()
{
InitializeComponent();
UrlTextBox.Text = #"enter URL here";
}
private void ImporButton_Click(object sender, EventArgs e)
{
try
{
String urlToListen = UrlTextBox.Text;
//Invoke MyListener
MyListener.StartListen(urlToListen); //assume this is implemented
}
catch (Exception exception)
{
string errorMsg = String.Format("An exception occured = {0}", exception);
MessageBox.Show(errorMsg);
}
}
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
}
}
so, what now ? how do i invoke the backgroundWorker1_DoWork ???
10x to anyone who can help
You need to call this method RunWorkerAsync
backgroundWorker1.RunWorkerAsync();
If you want to pass some argument into the handler DoWork via the DoWorkEventArgs, try the second overload of RunWorkerAsync:
backgroundWorker1.RunWorkerAsync(yourArgument);