我有2个表单,第一个form4是一个dataGridView,包含来自数据库的信息,当我clic on" New"按钮,form5显示一个公式,我应该填写然后clic在"添加"按钮,最后,我得到的结果应该出现在Form4的datagridView中。 那可能吗? 这是我的代码:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand sql = new SqlCommand("insert into journal values('" + textBox1.Text + "','" + textBox2.Text + "','" + comboBox2.SelectedItem.ToString() + "','" + comboBox1.SelectedItem.ToString() + "','" + checkBox1.Checked.ToString()+"','"+checkBox2.Checked.ToString()+"');", connection);
int o = sql.ExecuteNonQuery();
MessageBox.Show(o + " Le Fichier journal a ?t? ajout? avec succ?s");
connection.Close();
textBox1.Text = "";
textBox2.Text = "";
if(textBox1.Text ==" ")
{
MessageBox.Show("La saisie du code Journal est obligatoire!!");
}
affich();
}
private void affich()
{
try
{
pat = connectionString;
req = "SELECT * FROM journal";
con = new SqlConnection(pat);
con.Open();
dr = new SqlDataAdapter(req, con);
dr.Fill(ds, "journal");
Form4 Form4 = new Form4();//ceci va creer une nouvelle instance je ne veux pas avoir une nouvelleFen?te
Form4.journalDataGridView.DataSource = ds.Tables["journal"];
Form4.Show();
}
catch (Exception e) { MessageBox.Show("Base de donn?es non trouv?e", e.Message); }
}
和2种形式:
感谢帮助
答案 0 :(得分:3)
请尝试此代码方法:
private void affich()
{
try
{
pat = connectionString;
req = "SELECT * FROM journal";
con = new SqlConnection(pat);
con.Open();
dr = new SqlDataAdapter(req, con);
dr.Fill(ds, "journal");
Form4 obj= new Form4();//ceci va creer une nouvelle instance je ne veux pas avoir une nouvelleFenête
obj.journalDataGridView.DataSource = ds.Tables["journal"];
Form4.Show();
}
catch (Exception e) { MessageBox.Show("Base de données non trouvée", e.Message); }
}
答案 1 :(得分:1)
要求:Form5
中的按钮应在DataGridView
中的Form4
中添加结果,而不会创建Form4
的新实例
在Form4
中将Modifiers
的{{1}}属性更改为journalDataGridView
。
需要进行以下更改:
Public
如何从public partial class Form5 : Form
{
Form4 form4;
public Form5(Form4 f4)
{
InitializeComponent();
this.form4 = f4;
}
private void button2_Click(object sender, EventArgs e)
{
...
...
affich();
}
private void affich()
{
try
{
pat = connectionString;
req = "SELECT * FROM journal";
con = new SqlConnection(pat);
con.Open();
dr = new SqlDataAdapter(req, con);
dr.Fill(ds, "journal");
form4.journalDataGridView.DataSource = ds.Tables["journal"];
}
catch (Exception e) {
MessageBox.Show("Base de donn?es non trouv?e", e.Message);
}
}
}
创建Form5
实例:
在Form4.cs中:
Form4
或来自任何其他父母表格:
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
private void newButton_Click(object sender, EventArgs e)
{
Form5 form5 = new Form5(this);
form5.Show();
}
...
}