I have a second form that pops up upon clicking a button, a user can input some parameters for a method, save the input within a variable, and then I parse the result to an int ( thus so I can utilize it within my method ). Now, upon parsing it, the value appears to be NULL as oppose to what the user inputted within the textboxes.
var displayproperties = new int[3];
using (Form2 form = new Form2())
{
try
{
if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
int i = 0;
while (i == 0)
{
if (form.click) // ok button is clicked
{
// parse values
displayproperties[0] = int.Parse(form.Height);
displayproperties[1] = int.Parse(form.Width);
displayproperties[2] = int.Parse(form.Framerate);
goto break_0; // break out of loop ( loop is to check when button is clicked )
}
}
}
}
As you can see here, the values that the user inputs is Height,Width and Framerate respectively. It parses it to an int, as I explained, and stores it in the displayproperties int array.
This is the second form:
public string Height { get; set; }
public string Width { get; set; }
public string Framerate { get; set; }
public bool click = false;
public Form2()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e){}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Height = height.Text;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
Width = width.Text;
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
Framerate = framerate.Text;
}
public void OK_Click(object sender, EventArgs e)
{
click = true;
}
Ultimately, the values are then passed into this class:
public Class1(int width, int height)
However I get an out of range exception saying the value must be greater than zero. Goes without saying, the values I inputted were certainly greater than zero ( 800, 600, 60 respectively ) where 60 is used elsewhere.
Since my comment suggestion worked for you, I'll add it as an answer.
From what you've said, it sounds likely that you're not setting DialogResult anywhere, so your if statement is never being entered because the condition isn't met.
You should set the dialog result and close the form in OK_Click:
public void OK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
And then you should remove the extra code from your main form:
var displayproperties = new int[3];
using (Form2 form = new Form2())
{
try
{
if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// parse values
displayproperties[0] = int.Parse(form.Height);
displayproperties[1] = int.Parse(form.Width);
displayproperties[2] = int.Parse(form.Framerate);
}
}
}
The dialog result will serve as your click property so this is no longer required. By the way, I recommend switching to TryParse instead so that you can actively check if the input values are valid integers, as opposed to leaving it until exceptions are thrown.
An example of this:
string a = "hello"; // substitute user input here
int result;
if (!int.TryParse(a, out result))
{
MessageBox.Show($"{a} isn't a number!");
return;
}
MessageBox.Show($"Your integer is {result}");
If you're newish to programming, I recommend getting familiar with how to use the debugger. Setting a breakpoint and inspecting values as you stepped through the code would have revealed where the problem was very quickly. Microsoft have a tutorial for this.
Related
I'm just starting off with C# and I've been stuck trying to understand what I'm doing wrong for a couple of hours. I've tried so many different variations with no success so I wouldn't be surprised if I'm completely off at this point. What I'm trying to do is suppose to allow the user to enter a value then click one radio button in each of the groups. So the user is expected to make a selection in the group 1 radio buttons first which will be the original type of measurement that is being entered into the textbox. Then select from the group 2 radio buttons what they would like to convert the value entered into the textbox to (for ex. in. to cm.) and after selecting 1 radio button from each group. Click the convert button which then should show the conversion in the output label.
Any guidance would be appreciated, thanks!
public partial class Form1 : Form
{
const double INCHEStoCM = 2.54;
const double INCHEStoM = 0.0254;
const double FEETtoCM = 30.48;
const double FEETtoM = 0.3048;
public Form1()
{
InitializeComponent();
}
private void buttonExit_Click(object sender, EventArgs e)
{
//to exit
{
DialogResult respExit;
respExit = MessageBox.Show("Would you like to exit?", "Distance Converter", MessageBoxButtons.YesNo);
if(respExit==DialogResult.Yes)
{
this.Close();
}
}
}
private void buttonReset_Click(object sender, EventArgs e)
{
textBoxNumber.Clear();
labelOutput.Text = "";
textBoxNumber.Focus();
}
private void buttonConvert_Click(object sender, EventArgs e)
{
double inNumber = 0, outMetricValue = 0;
try // check if data is a number
{
inNumber = double.Parse(Text);
outMetricValue = double.Parse(Text);
}
catch
{
MessageBox.Show("Data entered must be a number", "Distance Converter");
buttonReset.PerformClick();
return;
}
// check number is > 0; <0 is error
if(inNumber<0)
{
MessageBox.Show("Value entered must be >0", "Distance Converter App");
buttonReset.PerformClick();
return;
}
if (radioButtonInches.Checked && radioButtonCm.Checked)
{
outMetricValue = inNumber * INCHEStoCM;
labelOutput.Text = outMetricValue.ToString("n");
}
}
}
}
I'm new to C# and I need this function for a program im working on for school. I need to make a new window pop up when i click a button, not a message box though like a forms window, one that i can design with text boxes and buttons. What is on the new pop up window depends on the previous window but i can figure that out.
Also I need a way to close the previous window once the new one appears
Here's my code:`
// This makes sure only one box is checked
private void MulCB_CheckedChanged(object sender, EventArgs e)
{
if( MulCB.Checked == true)
{
DivCB.Checked = false;
AddCB.Checked = false;
SubCB.Checked = false;
}
}
private void DivCB_CheckedChanged(object sender, EventArgs e)
{
if (DivCB.Checked == true)
{
MulCB.Checked = false;
AddCB.Checked = false;
SubCB.Checked = false;
}
}
private void AddCB_CheckedChanged(object sender, EventArgs e)
{
if (AddCB.Checked == true)
{
DivCB.Checked = false;
SubCB.Checked = false;
MulCB.Checked = false;
}
}
private void SubCB_CheckedChanged(object sender, EventArgs e)
{
if (SubCB.Checked == true)
{
DivCB.Checked = false;
AddCB.Checked = false;
MulCB.Checked = false;
}
}
private void oneDCB_CheckedChanged(object sender, EventArgs e)
{
if(oneDCB.Checked == true)
{
twoDCB.Checked = false;
threeDCB.Checked = false;
}
}
private void twoDCB_CheckedChanged(object sender, EventArgs e)
{
if ( twoDCB.Checked == true)
{
oneDCB.Checked = false;
threeDCB.Checked = false;
}
}
private void threeDCB_CheckedChanged(object sender, EventArgs e)
{
if (threeDCB.Checked == true)
{
oneDCB.Checked = false;
twoDCB.Checked = false;
}
}
// ends here
// Button operation
private void button8_Click(object sender, EventArgs e)
{
var form = new Form();
}
}
}
`
Thanks a lot!
Sal
The project is im supposed to make a quizzing program for kids. They should be able to choose 1 operation and the amount of digits the numbers will have. It then has to out put 10 random questions according to the selection made by the kid, then once they have completed the quiz, it should display their results and which questions they got wrong.
Assuming that the design of the window doesn't have to be completely dynamic, you can design it in Visual Studio (I'm assuming you did so with the first one). Then you can pass the results to the window. Like:
// Note: Form2 ist the name of your designed From
Form2 myform = new Form2();
this.Hide();
//You could pass the question settings like this
// 1 is for multiplication, 2 for division,3 for addition, 4 for substraction
myform.operation=1;
myform.digits=2
myform.Show();
And in the code of Form2:
namespace Yournamespace {
public partial class Form2: Form {
//Add these two lines about here
public static int operation;
public static int digits;
public Form2() {
InitializeComponent();
}
}
}
Then you can use the variables in Form2 and fill in the textbox or other elements you might design.
Also: You cloud use radio buttons instead of checkboxes as you then won't have you worry about unchecking the other checkboxes.
So basically im trying to make polygons with a name entered from Form2, called Apgabala_nosaukums (it's in my language, sorry for that). I have been trying to debug this, first 2 times the name entered from Form2 did get read and i was able to see that the name was added to the Polygon. But now it is not getting in the fromVisibleChanged anymore, ending in that the polygon is not getting name. Meaning that I cannot get the bool to true, so I could add 4 points and make a square or rectangle area out of them. Any ideas? Basically the btnAdd_Click function is not working properly, rest is working fine. Any ideas?
Form1 (Main form):
namespace GMapTest
{
public partial class Form1 : Form
{
GMapOverlay polygons = new GMapOverlay("polygons");
List<PointLatLng> points = new List<PointLatLng>();
double lat;
double lng;
int clicks = 0;
bool add = false;
string nosaukums;
public Form1()
{
InitializeComponent();
}
private void gMapControl1_Load(object sender, EventArgs e)
{
gmap.MapProvider = GoogleMapProvider.Instance;
GMaps.Instance.Mode = AccessMode.ServerOnly;
gmap.SetPositionByKeywords("Riga, Latvia");
gmap.ShowCenter = false;
gmap.Overlays.Add(polygons);
}
private void gmap_MouseDown(object sender, MouseEventArgs e)
{
if (add == true)
{
if (e.Button == MouseButtons.Left)
{
lat = gmap.FromLocalToLatLng(e.X, e.Y).Lat;
lng = gmap.FromLocalToLatLng(e.X, e.Y).Lng;
clicks += 1;
points.Add(new PointLatLng(lat, lng));
}
if (clicks == 4)
{
GMapPolygon polygon = new GMapPolygon(points, nosaukums);
polygons.Polygons.Add(polygon);
clicks = 0;
points.Clear();
add = false;
}
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
Apgabala_nosaukums addName = new Apgabala_nosaukums();
addName.ShowDialog();
addName.VisibleChanged += formVisibleChanged;
if (nosaukums != null)
{
this.add = true;
}
}
private void formVisibleChanged(object sender, EventArgs e)
{
Apgabala_nosaukums frm = (Apgabala_nosaukums)sender;
if (!frm.Visible)
{
this.nosaukums = (frm.ReturnText);
frm.Dispose();
}
}
}
}
Form2 (Apgabala_nosaukums):
namespace GMapTest
{
public partial class Apgabala_nosaukums : Form
{
public string ReturnText { get; set; }
public Apgabala_nosaukums()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.ReturnText = this.txtName.Text;
this.Visible = false;
}
}
}
The problem is in your btnAdd_Click function. When you call ShowDialog your other form is shown and the next line, addName.VisibleChanged += formVisibleChanged; isn't called until you close the new form. ShowDialog shows the form modally, you can't interact with the parent until you close the new form.
There are a couple ways you could fix this.
1) Subscribe to the VisibleChanged event before you show the form,
addName.VisibleChanged += formVisibleChanged;
addName.ShowDialog();
2) Call addName.Show() instead of addName.ShowDialog(). This shows the form in a non-modal way. The event will get subscribed to because execution continues in btnAdd_Click before the new form is closed. But, the parent form will be interactable, not sure if this is desired or not.
3) You could also get rid of the VisibleChanged event stuff and instead do ShowDialog and read the property after. This is what I'd recommend from seeing the code.
private void btnAdd_Click(object sender, EventArgs e)
{
Apgabala_nosaukums addName = new Apgabala_nosaukums();
addName.ShowDialog();
this.nosaukums = addName.ReturnText;
addName.Dispose();
}
I'm doing a "Who wants to be a millionaire"-like game and I'm stuck at how to check if the answer is the right answer or not.
I've made a struct that I can use to create some questions which looks like this:
struct Question
{
public string question, ansA, ansB, ansC, ansD;
public int correctAnswer;
}
Then I make questions like this:
Question ett = new Question();
ett.question = "Who is the richest?";
ett.ansA = "XXXX";
ett.ansB = "god";
ett.ansC = "vit";
ett.ansD = "röd";
ett.correctAnswer = 1;
And after that I put them in a list and retrieve a random question from there. The question in a label and the answers in four different buttons.
Random rnd = new Random();
int number = rnd.Next(0, NumberOfquestions+1);
var question = QuestionList[number];
lblquestion.Text = question.question;
button1.Text = question.ansA;
button2.Text = question.ansB;
button3.Text = question.ansC;
button4.Text = question.ansD;
The variable names aren't 100% correct because I've changed them for you to understand them since I have the variables in my language.
I'm stuck on how to check if the button clicked is right or not, and I have some thoughts about it but I'm unsure if that will work or if there are any better ways to do it.
One thing I thought was to make a method that check if its right, if the button return a value between 1-4 and check it against my int correctAnswer in the struct.
public int button1_Click(object sender, EventArgs e)
{
return 1;
}
Another thing I thought about was if I could make a method including all of the right answers in the game and search through if that match the text on my button?
Maybe not the best method to use.
namespace quiz
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
programmet();
}
public void btnNewGame_Click(object sender, EventArgs e)
{
}
public void BtnAvsluta_Click(object sender, EventArgs e)
{
this.Dispose();
this.Close();
}
public void programmet()
{
Question ett = new Question();
ett.fråga = "who is richest ?";
ett.svarA = "XXXX";
ett.svarB = "god";
ett.svarC = "vit";
ett.svarD = "röd";
ett.rättsvar = 1;
var QuestionList = new List<Question>();
QuestionList.Add(ett);
QuestionList.Add(tre);
QuestionList.Add(fyra);
QuestionList.Add(fem);
Random rnd = new Random();
int number = rnd.Next(0, numberOfQuestions -1);
var currentQuestion = QuestionList[number];
lblFråga.Text = currentQuestion.fråga;
button1.Text = currentQuestion.svarA;
button2.Text = currentQuestion.svarB;
button3.Text = currentQuestion.svarC;
button4.Text = currentQuestion.svarD;
}
public void button1_Click(object sender, EventArgs e)
{
/// here I want to use CurrentQuestion.question etc.
/// to do the "if(currentquestion.ansA == 1)"
}
}
}
Here is a possible solution:
Define a variable to store the current question (currentQuestion) that is accessible from the Click event handler of each button and from the method in which you select the question.
public void button1_Click(object sender, EventArgs e) {
if (currentQuestion.correctAnswer == 1)
CorrectAnswer();
else
WrongAnswer();
}
public void button2_Click(object sender, EventArgs e) {
// same for button2 ...
}
You could assign the Tags of your answer buttons, so button1.Tag = 1, button2.Tag = 2 etc. Then, for all your answer buttons, set their Click event to the same method, e.g.
void Answer_Click(object sender, EventArgs e)
In the method body, you can then access the Tag of the clicked button using...
int selectedAnswer = (int)((Button)sender).Tag;
To access your current question, make a private property or field in your Form1 class:
private Question CurrentQuestion;
and in your programmet() method, assign to it like this:
this.CurrentQuestion = QuestionList[number];
...so you can use
if (CurrentQuestion.correctAnswer == selectedAnswer) { ... }
Another way is when you're loading the answers onto the form set the appropriate button's tag to true and the rest false. Now in the common click event handler check the tag value of sender cast to a button and you have whether the answer is right
Why not just create two methods called CorrectAnswer() and IncorrectAnswer() and call the appropriate one from each button click. like so.
public void button1_Click(object sender, EventArgs e) {
//if answer is correct
CorrectAnswer();
public void button2_Click(object sender, EventArgs e) {
//if answer is incorrect
IncorrectAnswer();
hope this helps
I'm trying to make a "checkbox" that has a custom check image. I need it to toggle between checked and unchecked when the user clicks the picturebox. I've tried the following code, and the first click shows the checked image fine, however a second click does nothing. Any ideas?
private void pictureBox7_Click(object sender, EventArgs e)
{
if (pictureBox7.Image == Image.FromFile(checkedImg))
{
pictureBox7.Image = Image.FromFile(uncheckedImg);
}
else
{
pictureBox7.Image = Image.FromFile(checkedImg);
}
}
Your if statement is wrong as it is unlikely to return true because you are comparing instances of the Image class which you recreate every time. You could modify it like this:
private bool _pbChecked = false;
private void pictureBox7_Click(object sender, EventArgs e)
{
var pictureBox = (PictureBox)sender;
string imgPath = _pbChecked ? uncheckedImg : checkedImg;
pictureBox.Image = Image.FromFile(imgPath);
_pbChecked = !_pbChecked;
}