So I am having a bit of issue with this piece of code for a class of mine. I know it seems rather elementary but for the life of me I am not sure why I can't get it to work.
Essentially I have 6 radio buttons and depending on which one is selected I want to assign a value to an int variable. I want to return that value to another winForm which will do something else.
but for some reason it always returns 0.
some help would be greatly appreciated.
Thank you in advance..
int x = 0;
public int selectionDie1()
{
if (die1_1.Checked)
x = 1;
if (die1_2.Checked)
x = 2;
if (die1_3.Checked)
x = 3;
if (die1_4.Checked)
x = 4;
if (die1_5.Checked)
x = 5;
if (die1_6.Checked)
x = 6;
return x;
}
I like to also add that even if I change this to a void with no return value and place a label that would display the value of x on buttonclick, it still returns a 0.
I have even tried using just one radiobutton and see if that would work, nothing at all.
when I set x = 1000; and return that it works fine, so it has to do with the radio buttons
thank you
If I understand this correctly, you are attempting to use the variable x in your other form. You need to use the direct result of the selectionDie1 function.
public int selectionDie1()
{
if (die1_1.Checked)
return 1;
else if (die1_2.Checked)
return 2;
...
else
throw new exception("there was no item checked");
}
This way there is no variable to keep track of, or could be accessed from an outside location.
The other issue is that you are creating a form and then immediately checking for the selected item (if your comment is correct). You need to first create and show the form, give the user time to choose an option, and then do this function call (which might happen on a user selection, form close, button press, etc).
Related
I am trying to loop trough something 3 times and change the .text property of 3 element that have the names "label1", "label2" and "label3". I'm trying to add the 1,2,3 to the label but I can't get it to work.
this is what I'm trying to do:
the y is either 1,2 or 3
("label" + y).Text
I think you want this,so I make a simple code of it.
for(int i = 1; i <= 3; i++)
{
Console.WriteLine("label" + i);
}
if I understand correctly - you can do this using reflection:
var temp = (double)typeof(MyClass).GetProperty("label" + y).GetValue(myClassInstance);
if you change the type of MyClass to the class that holds your variable, myClassInstance to an instance of your class and the cast from double to your field type (which I'm guessing is some sort of WPF / Winforms control) you can get the variable by name.
It's important to note that your program will slow down if this is used often.
I have an array of buttons used to select items from an array.
What I'm trying to do is use one function to handle this, like the code below, instead of writing a lot of functions just doing a small job.
However, it seems all of those buttons are set to the last i and it gives an "array out of bound" exception every time I click on the button.
Is there any better way to do this?
I considered to search for the index of clicked button, but that feels weird to me and could be slow.
public Button[] MPS;
for(int i = 0; i < gm.MP.Length; i++)
{
MPS[i].onClick.AddListener(() => MPButtonHandle(i));
}
void MPButtonHandle(int i)
{
MP = gm.MP[i];
};
Basically you need to make a local copy of variable i:
public Button[] MPS;
for(int i = 0; i < gm.MP.Length; i++)
{
int j = i;
MPS[i].onClick.AddListener(() => MPButtonHandle(j));
}
void MPButtonHandle(int i)
{
MP = gm.MP[i];
};
The reason behind all of this is a mechanizm called closures. You can find more info about this here:c# closures
I have an array of textboxes in which they change dyanmically depending on what the user types in. Those textboxes contain a number which represents a score of an assignment. Those score are linked to a module object. So if the user has 3 modules; 2 assignments on the first and second module and 3 assignments on the third module; then in total there would be 7 textboxes created for the user to input all their assignment marks.
What I am trying to do is to create a keyup event handler in which it gets the number in typed in by the user, and then dynamically calls a method to display the average of the the module. This is what I have so far. The following method gets called whenever the user types in a character:
public void calculateLevel4Modules(int counter) {
//iterate through modules
//iterate through assignts in that module
//whilst iterating, check tb and set userscore
//after iterating, update overall label with regards to modulecounter
//int assignmentCounter = 0;
//Console.WriteLine("in If statement.. " + counter);
for (int moduleCounter = 0; moduleCounter < requiredLevelList().Count; moduleCounter++)
{
int totalNumberOfAssignmentsInCurrentModule = requiredLevelList().ElementAt(moduleCounter).Assignments.Count;
Console.WriteLine("total number of assignmetns: " + totalNumberOfAssignmentsInCurrentModule);
assignmentCounter = assignmentCounter + totalNumberOfAssignmentsInCurrentModule;
Console.WriteLine("assignment counter: " + totalNumberOfAssignmentsInCurrentModule);
if (counter < assignmentCounter)
{
Console.WriteLine("in If statement.. " + userMarksTBLvl4[moduleCounter].Text);
try
{
int userMark = int.Parse(userMarksTBLvl4[counter].Text);
requiredLevelList().ElementAt(moduleCounter).Assignments.ElementAt(counter).UsersScore = userMark;
double modAvg = requiredLevelList().ElementAt(moduleCounter).getModuleScoreOverall();
moduleOverallLvl4[moduleCounter].Text = modAvg.ToString();
break;
}
catch (FormatException) { break; }
}
else { }
}
it works fine if the user has one module but if the user has two or more, then I get an error in the following line:
requiredLevelList().ElementAt(moduleCounter).Assignments.ElementAt(counter).UsersScore = userMark;
I am getting an out of bounds exception. I know why; its because counter is basically the # of the textbox that was typed into but by me using counter, I am accessing something not within the assignments list. This is an example of when the problem occus:
The user has 2 modules. In each module there are 2 assignments thus 4 textboxes are been created with their index ranging from 0 - 3. If the user wants to type in their score of the first assignment on the second module, its basically trying to write to the third index in that element then it crashes since that module only consist of 2 assignments.
There are some strange things in your code that make it hard to answer. First, the code you posted doesn't compile, so we have no way to test it.
Several times you use code like:
requiredLevelList().ElementAt(moduleCounter)
I assume requiredLevelList is a method that returns a list of things. There is no reason to assume requiredLevelList returns the same list, or even lists with the same number of elements, each time you call it. Maybe it does in your particular case, but this is a dangerous thing to rely on. You should use a construct like:
foreach (var module in requiredLevelList())
{
int totalNumberOfAssignmentsInCurrentModule = module.Assignments.Count;
...
module.Assignments.ElementAt(counter).UsersScore = userMark;
...
}
Code like this:
Console.WriteLine("total number of assignmetns: " + totalNumberOfAssignmentsInCurrentModule);
is symptomatic of trying to debug something after it has crashed. That is extremely inefficient. Learn how to use a debugger; you will not become an effective programmer until you know how to do this.
requiredLevelList().ElementAt(moduleCounter).Assignments.ElementAt(counter).UsersScore = userMark;
You're probably getting an out-of-bounds exception here because counter is outside the indexes of Assignments. Since you never initialize or change counter, I have no way to know what it is or should be. A debugger will tell you this, use one.
the # of the textbox that was typed into but by me using counter, I am accessing something not within the assignments list.
OK, if you're typing something “not within the assignments list” then you have to test for that and decide what to do. Perhaps something like:
if (counter >= 0 && counter < module.Assignments.Count)
module.Assignments.ElementAt(counter).UsersScore = userMark;
else
throw new Exception("I really have no idea what you want to do here.");
This also looks wrong:
moduleOverallLvl4[moduleCounter].Text = modAvg.ToString();
You never tell us what moduleOverallLvl4 is, but here you're assuming it has the same size as what is returned by requiredLevelList(). Maybe they are in this particular case, but that is a dangerous assumption. If these values are related, moduleOverallLvl4 should be contained in whatever class implements requiredLevelList, and you should have a method that assigns getModuleScoreOverall() to the correct element of moduleOverallLvl4.
I have written a method in c# to get a count of a table, and saves the count in settings properties.
public static bool CompareCount(int? currentCount)
{
Properties.Settings.Default.Count = (int)currentCount;
Properties.Settings.Default.Save();
if (currentCount < Properties.Settings.Default.Count)
{
return false;
}
else
{
return true;
}
}
At first time if the count returned is 20. I will save it in the settings and I shud not compare that wiht the previous count. ON second time I want to compare the current count wiht the previoulsy saved count in settings. The above method should assign the current count for the first time . but on second time it shud compare.
thanks in advance.
First of all, think about what would happen when you cast the int? that's coming in to int if the parameter is null. It doesn't make sense to use a nullable parameter if you don't do anything with it later on. You should either change the parameter type to int or you could do this:
Properties.Settings.Default.Count = currentCount ?? 0;
Then, the method will always return true, as the if condition is always false - remember you're setting Properties.Settings.Default.Count to currentCount just two lines above that? So how should it ever be larger than currentCount?
You need to define for yourself how to determine "the first time" and "the second time". What's the condition to find out whether the method is run for the first time? For the code below I'll assume that there's some default value for Properties.Settings.Default.Count that helps you determine whether the method runs for the first time.
Then, from what you say, your code should look like this:
public static bool CompareCount(int? currentCount)
{
int countValue = currentCount ?? 0;
if (Properties.Settings.Default.Count == <some default value>)
{
Properties.Settings.Default.Count = (int)currentCount;
Properties.Settings.Default.Save();
}
else
{
return currentCount >= Properties.Settings.Default.Count;
}
}
What is your problem in implementing it? You have all the blocks already here at hand. Just reorder them properly.
If the problem is that the "int Count" defined in settings is "0" by default, you can change it i.e. to default to -1 so it obviously will be NOT a Count written before. Or, you can change it to int? to have default null..
Ask the current found Count to check if it is equal to the default value (zero, or not found or set your own once not found let say -1), so once not found you do not compare otherwise compare the values.
For Example:
public static bool CompareCount(int? currentCount)
{
int foundCount = ReadFoundCountFromProperties;
if (foundCount != 0)
{
Properties.Settings.Default.Count = (int)currentCount;
Properties.Settings.Default.Save();
if (currentCount < foundCount)
return false;
return true;
}
If I wanted to swap out part of a statement with a variable i.e.
tempCube.transform.parent = row(var would need to go here ie an int that is iterated with a for loop).transform;
How would I write this. Sorry for the really basic question, I have been using other languages too long and now I have gone back to c# I have almost forgotten everything I had learned.
"(i)" is the bit I want to swap out with a variable
eg
for(int i = 1; i <= 3; i++){ print row*(i)*.transform; }
Console:
(1,2,3)
(2,3,4)
(4,5,6)
You mean like:-
row1.transform;
row2.transform;
row3.transform;
...
If so, no, you can't replace that text at runtime. You should use a collection. Ideally make an IEnumerable out of them and use foreach:-
foreach (var x in new { row1, row2, row3 ... })
{
x.transform;
}
I am not sure what you mean, i hope you want to specify the index, is this what you are looking for (index is the int you mentioned)
tempCube.transform.parent = row[index].transform;