In my program there are multiple players who's stats can all be increased at the same time.
Player 1 is represented by staminaTextBox[0] skillTextBox[0] LuckTexBox[0]
Player 2 is represented by staminaTextBox[1] skillTextBox[1] LuckTexBox[1]
etc.
I need my IncreaseStat method to deal with 3 different type of Textbox Overload e.g. Stamina, Skill, Luck
private void StaminaIncBtn_Click(object sender, EventArgs e)
{
IncreaseStat(staminaText[0]);
}
private void LuckIncBtn_Click(object sender, EventArgs e)
{
IncreaseStat(luckText[0]);
}
private void IncreaseStat(TextBox statText)
{
for (int i = 0; i < 5 ; i++)
{
statText[i].Text = "Altered";
}
}
This method is used to increase all 5 players stats at the same time.
It works fine if they are not control arrays, however I need them to be. I get the error
"Cannot apply indexing with [] to an expression of type 'System.Windows.Forms.TextBox". It applies to that fact that inside the method I am saying statText[i].
I do not understand how to get around this problem. Any suggestions would be more than welcome.
Thank you for your time.
Would this be sufficient (with possible changes by yourself for your need)?
private void IncreaseStat() {
foreach (TextBox textBox in this.Controls.OfType<TextBox>().Where(x => x.Name.Contains("stamina") ||
x.Name.Contains("skill") ||
x.Name.Contains("Luck"))) {
textBox.Text = "Altered";
}
}
Related
I'm writing a FlashCard app in Windows Form.
Right now I'm trying to do is read word from string array and pass it to label. Then asking user to write the translation of this word. And finally pass the result to label box.
Here is my code:
public partial class EnglishPolishScreen : Form
{
//English words array
string[] words = new string[] { "word1", "word2", "word3", "word4" };
// meanings words array
string[] wordB = new string[] { "slowo1", "slowo2", "slowo3", "slowo4" };
int element = 0;
Thread thread;
public EnglishPolishScreen()
{
InitializeComponent();
}
private void CloseAppEvent(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
thread = new Thread(Threadd);
thread.Start();
}
private void Threadd()
{
englishWord.Text = words[element];
counterLabel.Text = element + 1 + " of " + words.Length;
if (answerBox.Text.Equals(wordB[element]))
{
resultLabel.Text = "Good";
element++;
}
else
resultLabel.Text = "Bad";
if (element == words.Length)
{
element = 0;
}
}
private void EnglishPolishScreen_Load(object sender, EventArgs e)
{
englishWord.Text = words[element];
}
Edited
Guys, Why I have to click two times in button to see next item from array? And why I can see "bad" answer straight after I click button? The "Good" answer shows up after second click.
Edited v2.xD
Sorted. Anyway is it good way to write code like this? If not how It could look better? Thanks
Regards
On button click, it is going through the whole for loop, i.e. the entire list of meanings, you would have to break the for loop as soon as a right match is found. So just use break; after resoultLabel.Text = "Good answer!";. Also as pointed out by #Neil, it is not good to use UI in a separate background thread.
By the way, I am not able to wrap my head around the logic of chances. For giving chances you would have to declare a global variable which would get added/subtracted when the a bad answer is found after Iterating through whole for loop, disallowing any further trial for the word.
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);
}
}
Hi I'm very new to c# and I was hoping someone could point me in the right direction. I have created a text box with the value "Total" set to 0 in my main class, and I have created a button "button1_Click" in my "AddFunds" class in which I want it to change the Total value by reading in what the user has in putted "Deposit" putting through a loop and incrementing the "Total". How do I get the AddFunds class to recognize the int Total in my main class?
public void textBox1_TextChanged(object sender, EventArgs e)
{
int Total = new int();
Total = 0;
////string str = Convert.ToString(Total);
////Total.Text = str;
}
public void button1_Click(object sender, EventArgs e)
{
for (int Deposit = 0; Deposit <= 0; ++Deposit)
{
Total = Deposit;
}
}
public void richTextBox1_TextChanged(int initialDeposit)
{
int Deposit = int.Parse(Console.ReadLine());
}
You have some ways of doing that, but remember if this classes you're talking about are forms, they need to exist simultaneously, anything else will end up on you trying to access a null reference.
You can create a public property Total on your main class and pass an instace of Main to AddFund
If the composition is the oposite as the above, and Main holds an instance of AddFund you can make Main inject itself on the other class or pass a Funciotn to AddFund so it can access the value
This one is the only one that doesn't sound like a code smell given the information you provided, abstract your logic to some classes that are not forms and manipulate them on the forms.
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.
So far I was putting all code that was reaction to event directly into event handling method.
Yesterday I saw somebody somewhere mentioning that only minimum of code should go there.
Is that true ? Or whats the best practice ?
e.g. which one of the examples is better from program-smooth-working point of view, and why, if you may:
Fig1:
private void MainForm_DragDrop(object sender, DragEventArgs e)
{
var DropPosX = e.X;
string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
for (int i = 0; i < s.Length; i++)
{
CheckFile(s[i])
LoadFile(s[i]);
// ..big chunk of code..
}
// ..big chunk of code..
}
Fig2:
DoDragDrop(int[] s, int DropPosX)
{
for (int i = 0; i < s.Length; i++)
{
CheckFile(s[i])
LoadFile(s[i]);
// ..big chunk of code..
}
// ..big chunk of code..
}
private void MainForm_DragDrop(object sender, DragEventArgs e)
{
var DropPosX = e.X;
string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
DoDragDrop(s, DropPos);
}
..or even
Fig3:
int DropPosX;
string[] s;
DoDragDrop()
{
for (int i = 0; i < s.Length; i++)
{
CheckFile(s[i])
LoadFile(s[i]);
// ...
}
// ...
}
private void MainForm_DragDrop(object sender, DragEventArgs e)
{
DropPosX = e.X;
s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
DoDragDrop();
}
Most event handlers essentially take the following two actions
Gather relevant data from the event, possible just that the event happened
Perform an action using the gathered data
It sounds like that person was suggesting that you break up these logical operations into 2 separate methods. This is sound reasoning but it is also an issue of style. It doesn't make your program more or less correct to do this. Although I generally find that code is more testable if you take this approach.
Specific to this sample though. I would not use instance variables in this case. The items being dragged and the position are relevant to the DoDragDrop method and should be passed as arguments. If that data needs to be persisted then DoDragDrop should be the one to set the instance values.
private void MainForm_DragDrop(object sender, DragEventArgs e)
{
int position = e.X;
string[] items = (string[])e.Data.GetData(DataFormats.FileDrop, false);
DoDragDrop(positon, items);
}
Yes you should try to keep a minimum in there.
It can get a bit messy if big chunk of code is say twiddling about with a load of internals (e.g. form controls, but you aim for as much as you can outside of the eventhandler.
All depends on what the big chunk of code is, but even a local private method is better than a huge lump of code in and eventHandler.
If say you were grabbing UI properties to store them in another class. Add a method to it, that takes them as arguments.
If it's a lot of UI stuff, look at a UserControl.
The main reason to do it, is testing UI is a major pain, so the less logic in the UI, the easier the job.