First, sorry for my English, it's not my first language.
I'm on the first grade of high school, and at my college we have a certificate program of three years in system analysis and development, along with the normal classes.
We are just starting learning c# at the course, but since we have some free time at the lab we started "playing" with winforms. I prefer to look at the code or google the error instead of asking, but this time i really can't figure what's wrong.
When i was using only one form, to get the input and show all users' information in real time (without a combobox, just labels), it all worked fine. What I want to do is, take input of five users, and , if the fields are filled correctly, add the first name of the user as an item to the combobox, and he can see the name/sex/age of previous users browsing the combobox items.
The Form1's code:
public partial class Form1 : Form
{
Form2 frm2 = new Form2();
public Form1()
{
InitializeComponent();
}
private void label9_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
variaveis.i++;
variaveis.nome[variaveis.i] = textBox1.Text;
variaveis.sobrenome[variaveis.i] = textBox2.Text;
variaveis.sexo[variaveis.i] = comboBox1.Text;
if (textBox3.Text != null)
variaveis.idade[variaveis.i] = textBox3.Text;
double num;
bool isnum = double.TryParse(variaveis.idade[variaveis.i], out num);
Form2 frm2 = new Form2();
frm2.Update();
if (variaveis.nome[variaveis.i]!=null && variaveis.sobrenome!=null && variaveis.idade[variaveis.i] != null && isnum)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
comboBox1.Refresh();
frm2.comboBox1.Items.Add(variaveis.nome[variaveis.i]); //Only works with the first input
if (variaveis.i == 1)
{
frm2.Show();
frm2.Location = new Point(this.Left + this.Width, this.Top);
frm2.Height = this.Height;
frm2.label6.Text = variaveis.nome[variaveis.i];
frm2.label7.Text = variaveis.sobrenome[variaveis.i];
frm2.label8.Text = variaveis.sexo[variaveis.i];
frm2.label9.Text = variaveis.idade[variaveis.i];
}
}
else
{
variaveis.i--;
MessageBox.Show("Preencha todos os campos",
"Erro");
}
if (variaveis.i >= 5)
{
button1.Enabled = false;
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
comboBox1.Refresh();
}
}
The Form2's code:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label6.Text = variaveis.nome[comboBox1.SelectedIndex + 1]; // i don't even know if i can use an array like this
label7.Text = variaveis.sobrenome[comboBox1.SelectedIndex + 1];
label8.Text =variaveis.sexo[comboBox1.SelectedIndex + 1];
label9.Text = variaveis.idade[comboBox1.SelectedIndex + 1];
}
The variables class (I thought would be easier to work this way if I'm using multiple forms, if I'm wrong, correct me):
class variaveis
{
public static string[] nome = new string[5]; //name
public static string[] sobrenome = new string[5]; //last name
public static string[] sexo = new string[5]; //gender
public static string[] idade = new string[5]; //age(string, checked with tryparse)
public static int i = 0;
}
Sorry if it's a noob question or if the error is obvious, but I started working with WinForms a couple weeks ago.
EDIT:
So the problems now are:
-Sometimes the program throw me the error even when all conditions are apparently fulfilled.
-Can't add items to a combobox in another form. Tried this:
public void AddItem(object item)
{
comboBox1.Items.Add(variaveis.nome[variaveis.i]);
}
Calling it in Form1:
frm2.AddItem(variaveis.nome[variaveis.i]);
The syntax seems correct, but nothing happens.
If you set it up like this, i think it is easier to address your data.
public class Person
{
public string Nome {get; set;}
public string Sobrenome {get; set;}
public string Sexo {get; set;}
public string Idade {get; set;}
}
public class Variaveis
{
public Person[] People {get; set;}
public Variaveis
{
People = new Person[5];
}
}
Now you can access the data like so:
var myName = Variaveis.People[2].Nome;
I edited some things and solved the "if" problem . The new code:
public partial class Form1 : Form
{
public string[] nome = new string[5];
public string[] sobrenome = new string[5];
public string[] sexo = new string[5];
public string[] idade = new string[5];
public int i = 1;
public Form1()
{
InitializeComponent();
}
private void label9_Click(object sender, EventArgs e)
{
}
public void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2(this);
nome[i] = textBox1.Text;
sobrenome[i] = textBox2.Text;
sexo[i] = comboBox1.Text;
idade[i] = textBox3.Text;
double num;
bool isnum = double.TryParse(idade[i], out num);
if (textBox1.Text !=null && textBox2.Text!=null && textBox3 != null && isnum == true)
{
frm2.comboBox1.Items.Add(textBox1.Text);
frm2.comboBox1.Update();
comboBox1.Update();
textBox4.Text = Convert.ToString(i); // just to check the variable's value, since they dont appear in the debugger tool
if (i == 1)
{
frm2.Show();
frm2.Location = new Point(this.Left + this.Width, this.Top);
frm2.Height = this.Height;
}
frm2.label6.Text = nome[i];
frm2.label7.Text = sobrenome[i];
frm2.label8.Text = sexo[i];
frm2.label9.Text = idade[i];
frm2.comboBox1.SelectedIndex = frm2.comboBox1.SelectedIndex + 1;
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
++i;
}
if(isnum == false && textBox1.Text == null && textBox2.Text == null && textBox3 == null)
{
MessageBox.Show("Preencha todos os campos", "Erro");
}
if (i >= 5)
{
button1.Enabled = false;
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
comboBox1.Refresh();
}
private void Form1_Load(object sender, EventArgs e)
{
}
I've noticed that all controls(not just combobox1) only respond to the first command coming from another form. If i put a textbox in form2 and call:
frm2.textBox1.Text = i;
it's going to show "1" forever. How do i solve this?
Solved the problem by myself, by adding this:
public partial class Form2 : Form
{
Form1 f1;
public Form2(Form1 f1)
{
InitializeComponent();
this.f1 = f1;
This:
public partial class Form1 : Form
{
private Form2 frm2;
and this:
public Form1()
{
InitializeComponent();
frm2 = new Form2(this);
}
The complete code with some improvements:
Form1:
public partial class Form1 : Form
{
private Form2 frm2;
public string[] nome = new string[6];
public string[] sobrenome = new string[6];
public string[] sexo = new string[6];
public string[] idade = new string[6];
public int i = 0;
public Form1()
{
InitializeComponent();
frm2 = new Form2(this);
}
public void button1_Click(object sender, EventArgs e)
{
++i;
nome[i] = textBox1.Text;
sobrenome[i] = textBox2.Text;
sexo[i] = comboBox1.Text;
idade[i] = textBox3.Text;
double num;
bool isnum = double.TryParse(idade[i], out num);
if (textBox1.Text !=null && textBox2.Text!=null && textBox3 != null && isnum == true)
{
frm2.comboBox1.Items.Add(textBox1.Text);
frm2.comboBox1.Update();
comboBox1.Update();
if (i == 1)
{
frm2.Show();
frm2.Location = new Point(this.Left + this.Width, this.Top);
frm2.Height = this.Height;
}
frm2.label6.Text = nome[i] + " " + sobrenome[i];
frm2.label8.Text = sexo[i];
frm2.label9.Text = idade[i];
frm2.comboBox1.SelectedIndex = frm2.comboBox1.SelectedIndex + 1;
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
}
if(isnum == false && textBox1.Text == null && textBox2.Text == null && textBox3 == null)
{
MessageBox.Show("Preencha todos os campos", "Erro");
--i;
}
if (i >= 5)
{
button1.Enabled = false;
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
comboBox1.Refresh();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
Form2:
public partial class Form2 : Form
{
Form1 f1;
public Form2(Form1 f1)
{
InitializeComponent();
this.f1 = f1;
comboBox1.Items.Add("Usuários");
}
private void Form2_Load(object sender, EventArgs e)
{
}
public void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex != 0)
{
label6.Text = f1.nome[comboBox1.SelectedIndex] + " " + f1.sobrenome[comboBox1.SelectedIndex];
label8.Text = f1.sexo[comboBox1.SelectedIndex];
label9.Text = f1.idade[comboBox1.SelectedIndex];
}
else
{
label6.Text = " ";
label8.Text = " ";
label9.Text = " ";
}
}
}
Thanks for the help anyway.
Related
i make class for table in my DB
namespace WindowsFormsApp1.Database {
class Ques
{
public int id;
public string title;
public Illnesses(int id,string title)
{
this.id = id;
this.title = title;
}
public static Ques[] getAll()
{
Ques[] arr = new Ques[100];
connection con1 = new connection();
MySqlCommand command = new MySqlCommand("SELECT * FROM ques;", con1.mycon());
MySqlDataReader reader = command.ExecuteReader();
int counter = 0;
while (reader.Read())
{
Ques= new Ques(reader.GetInt32(0), reader.GetString(1));
arr[counter++] = temp;
}
con1.con.Close();
return arr;
}
} }
and in form1 i called my Table Rows in database by Array to show in button name like text when i run the program and this work perfectly then transfer me to form2
namespace WindowsFormsApp1 {
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Ques[] ques= Ques.getAll();
button1.Text = ques[0].title;
button2.Text = ques[1].title;
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
this.Hide();
}
private void button2_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
this.Hide();
}
} }
And This is The Run,
The Problem is i need to make if condition in form2 depend on (button 1, 2 OR rows i called from DB in buttons) That in from1
To output different result in my Form2
my Form2
namespace WindowsFormsApp1 {
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
Form1 form1 = new Form1();
}
private void Form2_Load(object sender, EventArgs e)
{
Ques[] ques= Ques.getAll();
if (???????????)
{
button1.Text = ques[2].title;
label1.Text = "this is ans Q1";
}
else if (????????????)
{
button1.Text = ques[3].title;
label1.Text = "this is ans Q2";
}
}
shape of form 2
So what i should write in condition of form2 (place of question marks ??????????)
Thank everyone who can help :)
We can determine which button is clicked and button text is equal to the question text to write the condition.
You could define some property or fields in the form1. Then you could use Application.OpenForms method to access the property.
Key code:
form1.btn1text== "This is my q1" && form1.bt1clicked==true
form1.btn2text == "This is my q2" && form1.bt2clicked == true
Here is a code example you could refer to.
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string btn1text { get; set; }
public string btn2text { get; set; }
public bool bt1clicked = false;
public bool bt2clicked = false;
private void button1_Click(object sender, EventArgs e)
{
bt1clicked = true;
Form2 f2 = new Form2();
f2.Show();
this.Hide();
}
private void button2_Click(object sender, EventArgs e)
{
bt2clicked = true;
Form2 f2 = new Form2();
f2.Show();
this.Hide();
}
private void Form1_Load(object sender, EventArgs e)
{
Ques[] ques = Ques.getAll();
button1.Text = ques[0].title;
button2.Text = ques[1].title;
btn1text = button1.Text;
btn2text = button2.Text;
}
Form2:
private void Form2_Load(object sender, EventArgs e)
{
Form1 form1 = (Form1)Application.OpenForms["Form1"];
Ques[] ques = Ques.getAll();
if (form1.btn1text== "This is my q1" && form1.bt1clicked==true)
{
button1.Text = ques[2].title;
label1.Text = "this is ans Q1";
}
else if (form1.btn2text == "This is my q2" && form1.bt2clicked == true)
{
button1.Text = ques[3].title;
label1.Text = "this is ans Q2";
}
}
Tested result:
I'm very new to programming and I am writing a short hangman game for my programming class, I have two private voids, one when you change the text in the textbox for the correct answer and one for when you guess a character. I need to transfer the variable "svar" from the first instance to the other, when I try to use the variable "svar" in the second instance I get the error message "The name "svar" does not exist in the current context"
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void TbxSvar_TextChanged(object sender, EventArgs e)
{
if (tbxSvar.TextLength == 6)
{
pbxGubbe.Top = 6;
tbxVisa.Text = "??????";
tbxGissa.Enabled = true;
string svar = tbxSvar.Text;
tbxSvar.Text = "";
}
else
{
tbxVisa.Text = "";
}
}
private void TbxGissa_TextChanged(object sender, EventArgs e)
{
if (tbxGissa.Text == "") return;
string gissning = tbxGissa.Text;
int index = svar.indexOf(gissning);
}
}
You have defined svar as a variable in a method so it won't be visible elsewhere (unless you pass it as a method argument). Instead define it as a field in your class.
public partial class Form1 : Form
{
string svar; // <----------- place here. Now it is a 'field'
public Form1()
{
InitializeComponent();
}
private void TbxSvar_TextChanged(object sender, EventArgs e)
{
if (tbxSvar.TextLength == 6)
{
pbxGubbe.Top = 6;
tbxVisa.Text = "??????";
tbxGissa.Enabled = true;
svar = tbxSvar.Text; // <---------- use svar here
tbxSvar.Text = "";
}
else
{
tbxVisa.Text = "";
}
}
private void TbxGissa_TextChanged(object sender, EventArgs e)
{
if (tbxGissa.Text == "") return;
string gissning = tbxGissa.Text;
int index = svar.indexOf(gissning); // <---------- ...and here
}
}
I have a List of Objects. What I want to do:
Build a Dialog Box which shows a Radio Button for each element in the given List and returning the selected element/value by clicking on OK-Button.
Thanks in Advance.
Here is a quick example of creating your own form and getting a value from it.
Form1.cs:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
frmTest frmTest = new frmTest();
DialogResult dr = frmTest.ShowDialog();
if(dr == System.Windows.Forms.DialogResult.OK)
{
string value = frmTest.GetValue();
MessageBox.Show(value);
}
}
}
Form1 View:
public partial class frmTest : Form
{
private string _value { get; set; }
public frmTest()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton radioButton = (RadioButton)sender;
this._value = radioButton.Text; // Assign the radio button text as value Ex: AAA
}
public string GetValue()
{
return this._value;
}
}
You have to make sure that all radio buttons are using radioButton_CheckedChanged for the CheckedChanged event.
Form2 View:
Output:
build your own form and add a public variable "a string for example" called "Result"
public partial class YourDialog:Form
{
public string Result = "";
public YourDialog()
{// add all the controls you need with the necessary handlers
//add the OK button with an "On Click handler"
}
private void OK_Button_Click(object sender, EventArgs e)
{
//set the Result value according to your controls
this.hide();// will explain in the main form
}
}
// in your main form
private string GetUserResult()
{
YourDialog NewDialog = new YourDialog();
NewDialog.ShowDialog();//that's why you only have to hide it and not close it before getting the result
string Result = NewDialog.Result;
NewDialog.Close();
return Result;
}
OOps! I came back just to see there are already 2 answers! How ever, I want to post my version, which can build controls according to list of strings:
//dialog form
public partial class frmDialogcs : Form
{
public string selectedString;
//keep default constructor or not is fine
public frmDialogcs()
{
InitializeComponent();
}
public frmDialogcs(IList<string> lst)
{
InitializeComponent();
for (int i = 0; i < lst.Count; i++)
{
RadioButton rdb = new RadioButton();
rdb.Text = lst[i];
rdb.Size = new Size(100, 30);
this.Controls.Add(rdb);
rdb.Location = new Point(20, 20 + 35 * i);
rdb.CheckedChanged += (s, ee) =>
{
var r = s as RadioButton;
if (r.Checked)
this.selectedString = r.Text;
};
}
}
private void btnOK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
}
}
//in main form
private void button1_Click(object sender, EventArgs e)
{
var lst = new List<string>() { "a", "b", "c" };
frmDialogcs dlg = new frmDialogcs(lst);
if (dlg.ShowDialog() == DialogResult.OK)
{
string selected = dlg.selectedString;
MessageBox.Show(selected);
}
}
I'm new to c# and I tried making a simple program. After I click the button, the values won't update with their actual value, so I have to click twice to make them actually work. Here's my code:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private static int p;
private static int money;
public Form1()
{
InitializeComponent();
p = 0;
money = 100;
}
private void button1_Click(object sender, EventArgs e)
{
m.Text = money.ToString();
ex.Text = p.ToString();
if (checkBox1.Checked && checkBox2.Checked)
{
MessageBox.Show("You cannot select both.", "Nope");
}
else if (checkBox1.Checked)
{
p += 2;
}
else if (checkBox2.Checked)
{
money -= 50;
p += 10;
}
else
{
return;
}
}
}
}
You need to update the text after updating the value
if (checkBox1.Checked & checkBox2.Checked)
{
MessageBox.Show("You cannot select both.", "Nope");
}
....
m.Text = money.ToString();
ex.Text = p.ToString();
can I pass EditQuestionMaster(int qid_value) this qid_value ,within this private void button1_Click(object sender, EventArgs e) button click ,if yes than how can i do this so that I can UpdateQuestion properly
public partial class EditQuestionMaster : Form
{
DbHandling db = new DbHandling();
public EditQuestionMaster(int qid_value)
{
InitializeComponent();
string subNtop = db.GetEditSubNTopic(qid_value);
string[] subNtopData = subNtop.Split('~');
cmbSubject.Text = subNtopData[2];
}
private void button1_Click(object sender, EventArgs e)
{
int qid = ; //here i want the value of int qid_value
string AnsOp = "";
if (radioButton1.Checked == true)
AnsOp = "1";
else if (radioButton2.Checked == true)
AnsOp = "2";
else if (radioButton3.Checked == true)
AnsOp = "3";
else if (radioButton4.Checked == true)
AnsOp = "4";
else
{
MessageBox.Show("Answer Option Not Selected");
return;
}
string Marks = cmbMarks.SelectedItem.ToString();
if (db.UpdateQuestion(qid, txtQuestion.Text, txtOption1.Text, txtOption2.Text, txtOption3.Text, txtOption4.Text, AnsOp, Marks, "T"))
MessageBox.Show("Question Updated Successfully");
else
MessageBox.Show("Failed to Update Question");
}
}
thanks in advance for any help
public partial class EditQuestionMaster : Form
{
DbHandling db = new DbHandling();
int qid; // here is the class variable
public EditQuestionMaster(int qid_value)
{
InitializeComponent();
this.qid = qid_value; // set the value here
string subNtop = db.GetEditSubNTopic(qid_value);
string[] subNtopData = subNtop.Split('~');
cmbSubject.Text = subNtopData[2];
}
private void button1_Click(object sender, EventArgs e)
{
qid // use it here
Expanding on chancea's answer:
You can define a business object to handle the updates like so:
public class QuestionEditor
{
DbHandling db = new DbHandling();
int questionId;
public QuestionEditor(int questionId)
{
this.questionId = questionId;
}
public void SetAnswer(string answerOption)
{
db.UpdateQuestion(qid, answerOption);
}
}
When your form is created, have it create a new instance of your business object:
public partial class EditQuestionMaster : Form
{
QuestionEditor editor;
public EditQuestionMaster(int qid_value)
{
InitializeComponent();
editor = new QuestionEditor(qid_value);
}
}
Now other methods in your form can call into the editor to perform operations.
private void button1_Click(object sender, EventArgs e)
{
string answerOption;
// switch populates answerOption
editor.SetAnswer(answerOption);
}
By moving your logic to perform updates away from the form where the user interacts is called an abstraction. This abstraction allows the UI code to evolve somewhat independently of how the question data is accessed/stored. This is the basis for n-Tier architecture.