Sending Data Between Two Forms C# - c#

Click to see problem explain by Image i have two form ...
on form1 there is a submit button which when pressed form2 should be open with username textbox and submit button ....
when user press submit button form1 will be appeared again and button text will be change to username and new sign up button will appear ....
it works for first press but on second button press first button text goes to default text , how to fix this ?
class 1
namespace Internship_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string b;
public Form1(Form2 obj)
{
InitializeComponent();
if(button1.Name == obj.b2)
{
button1.Text = obj.username;
button2.Visible = true;
}
else if(button2.Name == obj.b2)
{
button2.Visible = true;
button2.Text = obj.username;
button3.Visible = true;
}
else if (button3.Name == obj.b2)
{
button2.Visible = true;
button3.Visible = true;
button3.Text = obj.username;
button4.Visible = true;
}
else if (button4.Name == obj.b2)
{
button2.Visible = true;
button3.Visible = true;
button4.Visible = true;
button4.Text = obj.username;
button5.Visible = true;
}
else if (button4.Name == obj.b2)
{
button2.Visible = true;
button3.Visible = true;
button4.Visible = true;
button5.Visible = true;
button5.Text = obj.username;
}
}
private void button1_Click(object sender, EventArgs e)
{
this.b = ((Button)sender).Name;
Form2 obj = new Form2(this);
obj.ShowDialog();
this.Hide();
}
}
}
class 2
namespace Internship_Test
{
public partial class Form2 : Form
{
string[] user = new string[5];
public Form2()
{
InitializeComponent();
}
public string b2;
public Form2(Form1 obj)
{
InitializeComponent();
b2 = obj.b;
}
public string username;
private void button1_Click(object sender, EventArgs e)
{
username = textBox2.Text;
Form1 obj = new Form1(this);
obj.Show();
this.Hide();
}
}
}[Click to see problem explain by Image ][1]

As response on your question/bug, like Mong Zhu pointed out:
Your bug is found here:
class 2
namespace Internship_Test
{
public partial class Form2 : Form
{
string[] user = new string[5];
public Form2()
{
InitializeComponent();
}
public string b2;
private Form1 _form1; // you need to create a field for the form1
public Form2(Form1 form1)
{
InitializeComponent();
b2 = obj.b;
_form1 = form1;
}
public string username;
private void button1_Click(object sender, EventArgs e)
{
username = textBox2.Text;
//Form1 obj = new Form1(this);
// instead of creating a new form, just pop it up:
_form1?.Show();
this.Hide();
}
}
}
And you should change the obj.ShowDialog(); to obj.Show();

Some questions:
Why would you hide the form1?
Why are you pass an instance of Form2 into the constructor of Form1?
I would implement it like:
public class Form1 : Form
{
private void button1_Click(object sender, EventArgs e)
{
using(var form2 = new Form2())
{
// if you want to fill the username before popup..
// do it here:
// form2.UserName = textBox2.Text;
var result = form2.ShowDialog();
if(result != DialogResult.OK)
return;
textBox2.Text = form2.UserName;
}
}
}
public class Form2 : Form
{
public string UserName
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
}

Related

c# winforms, I want to pass a primitive variable by Ref from a Form1 to another Form2's construct, and have the ability to alter its value

Form1 has the following code :
private void deleteMem_Click(object sender, EventArgs e)
{
bool delete = false;
choiceCheck choiceCheck = new choiceCheck(ref delete,"Supprimer le membre", "Êtes-vous sûr de vouloir supprimer le membre (" + CDMDisplay.Text + ") " + FNDisplay.Text + " " + LNDisplay.Text, "Supprimer", "Annuler");
choiceCheck.ShowDialog();
if (!delete) return;
...
and Form2 has :
public bool accept;
public choiceCheck(ref bool accept, string title, string message, string yesText, string noText)
{
InitializeComponent();
this.Text = title;
this.message.Text = message;
this.yesButton.Text = yesText;
this.noButton.Text = noText;
this.accept = accept;
}
private void yesButton_Click(object sender, EventArgs e)
{
accept = true;
this.Close();
}
private void noButton_Click(object sender, EventArgs e)
{
accept = false;
this.Close();
}
Form2 is like MessageBoxButtons.YesNo but as a Form.
I want to pass ref of delete to Form2 and have it alter its value.
I could make 'bool delete' a public variable and then alter it from Form2 as a solution, but is there any way to alter variable delete without declaring it public ?
That is not at all how this pattern is supposed to work. You need to either use DialogResut to return a yes/no, or have a property available with the result when the form closes.
MainForm.cs
For example, here is the main form which calls the confirmation form and depending on the DialogResult value it branches one way or another.
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ConfirmForm dlg = new ConfirmForm()
{
Title = "Confirm Membership",
Message = "By accepting this membership you ...",
YesText = "Confirm",
NoText = "Cancel",
};
if (dlg.ShowDialog() == DialogResult.Yes)
{
// accepted
label1.Text = "Accepted";
}
else
{
// canceled
label1.Text = "Canceled";
}
}
}
ConfirmForm.cs
and here is the confirmation form with the logic to handle setting the text labels and setting the proper value in DialogResult
public partial class ConfirmForm : Form
{
public ConfirmForm()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.AcceptButton = yesButton;
this.CancelButton = noButton;
yesButton.Click += (s, ev) =>
{
DialogResult = DialogResult.Yes;
this.Close();
};
noButton.Click += (s, ev) =>
{
DialogResult = DialogResult.No;
this.Close();
};
}
public string Message {
get => messageLabel.Text;
set => messageLabel.Text = value; }
public string YesText
{
get => yesButton.Text;
set => yesButton.Text = value;
}
public string NoText {
get => noButton.Text;
set => noButton.Text = value; }
public string Title {
get => Text;
set => Text = value; }
}

how to call value that called from DB by array in form1 and used it to make condition in form2 by C#

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:

Pass value from datagridview to textbox on other form

I have Form1 that has textbox; Form2(current form) has datagridview and button Choose. when i run Form1 that shows in new (nothing data that i wrote on form)
How can i pass value from Form2 to Form1 that keeps all data.
public void btnChoose_Click(object sender, EventArgs e)
{
Form1 form = new Form1;
form.txtMaKeHoach.Text = "value";
form.Show();
this.Close();
}
I hope this is what you are searching for...
Code for Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Form2 frm = new Form2();
DialogResult res = frm.ShowDialog();
if (res != System.Windows.Forms.DialogResult.OK)
{
frm.Dispose();
return;
}
this.txtMaKeHoach.Text = frm.ChosenEntry;
frm.Dispose();
}
}
Code for Form2:
public partial class Form2 : Form
{
private string _ChosenEntry = "";
public Form2()
{
InitializeComponent();
}
private void btnChoose_Click(object sender, EventArgs e)
{
//...
_ChosenEntry = this.dataGridView1.SelectedCells[0].Value.ToString();
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
public string ChosenEntry
{
get { return _ChosenEntry; }
}
}

Status variable

I'm programming a windows application (C#) that can only have 3 forms open.
When I click on the button of form1, form2 will open but it only open once.
I don't know why this is happening.
Can you please help me?
Thanks!
This is my code of form1:
public partial class Form1 : Form
{
bool form2Opend = false;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (!form2Opend)
{
Form2 f2 = new Form2(this);
f2.Show();
form2Opend = true;
string data = this.textBox1.Text;
f2.TextInTextBox(data);
}
}
public void TextInTextBox(string text)
{
this.textBox1.Text = tekst;
}
public void putStatusToOff()
{
this.form2Opend = false;
}
}
And here is my code from form2
public partial class Form2 : Form
{
private Form1 f1;
public Form2(Form1 giveToForm)
{
f1 = giveToForm;
InitializeComponent();
}
public void TextInTextBox(string tekst)
{
this.textBox1.Text = text;
}
private void button1_Click(object sender, EventArgs e)
{
string dataFromForm2 = this.textBox1.Text;
f1.TextInTextBox(dataFromForm2);
f1.putStatusToOff();
this.Close();
}
}
In your button1_Click method you check a status variable form2Opend and only open the form if this variable is set to false. If you want multiple instances of Form2 you have to remove that check:
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(this);
f2.Show();
string data = this.textBox1.Text;
f2.TextInTextBox(data);
}

Can't figure what's wrong with my code

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.

Categories