简体   繁体   English

从C#中的其他表单更新datagridview

[英]Update datagridview from other form in C#

To make it short, I have try solutions from other post but I cannot make it work. 简而言之,我尝试了其他帖子中的解决方案,但无法使其正常工作。 I am new to programming and I have been given a task from my work to make a software. 我是编程新手,我的工作是开发软件。

I have created two forms, in which first form is called AddNewUser and the other is called RegistrationPopOut where the latter form will pop out if user clicked Register on AddNewUser form. 我创建了两种形式,其中一种形式称为AddNewUser,另一种形式称为RegistrationPopOut,如果用户单击AddNewUser表单上的Register,则后者会弹出。

I want the datagridview in AddNewUser automatically updated itself if "save" is clicked on RegistrationPopOut 我希望如果在RegistrationPopOut中单击“保存”,则AddNewUser中的datagridview会自动更新

Here is the code for AddNewUser: 这是AddNewUser的代码:

       private void Register_Click(object sender, EventArgs e)
    {
        if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "" || comboBox1.Text == "" || comboBox2.Text == "" || comboBox3.Text == "")
        {

            MessageBox.Show("Please fill in every fields");
        }
        else
        {
            int i = 0;
            SqlCommand cmd = con.CreateCommand(); //Creates and returns a SqlCommand object associated with the SqlConnection.
            cmd.CommandType = CommandType.Text; //CommandType = Specifies how a command string is interpreted. 
            cmd.CommandText = "select * from registration where username='" + textBox3.Text + "' or idno='" + textBox2.Text + "'";
            //cmd.CommandText = "select * from registration where username='" + textBox3.Text + "'";
            cmd.ExecuteNonQuery(); //used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected. 
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            i = Convert.ToInt32(dt.Rows.Count.ToString());
            if (i == 0) //If ok nada masalah register
            {
                SqlCommand cmd1 = con.CreateCommand(); //Creates and returns a SqlCommand object associated with the SqlConnection.
                cmd1.CommandType = CommandType.Text; //CommandType = Specifies how a command string is interpreted. 
                cmd1.CommandText = "insert into registration values('" + textBox3.Text + "','" + textBox4.Text + "','" + textBox1.Text + "','" + textBox2.Text + "','" + comboBox1.Text + "','" + comboBox2.Text + "','" + comboBox3.Text + "')";
                cmd1.ExecuteNonQuery(); //used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected.

                textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; comboBox1.Text = ""; comboBox2.Text = ""; comboBox3.Text = "";
                display();

                MessageBox.Show("Successfully registered");
            }
            else //if ada masalah register
            {
                MessageBox.Show("User already registered");
            }

        }
    }

   private void display()
    {
        SqlCommand cmd = con.CreateCommand(); //Creates and returns a SqlCommand object associated with the SqlConnection.
        cmd.CommandType = CommandType.Text; //CommandType = Specifies how a command string is interpreted. 
        cmd.CommandText = "select IDNO as 'Employee ID',Username,Name as 'Full Name',Istana,Position,Area from registration";
        //cmd.CommandText = "select * from registration where username='" + textBox3.Text + "'";
        cmd.ExecuteNonQuery(); //used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected. 
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        dataGridView1.DataSource = dt;

    }

    private void AddNewUser_Load(object sender, EventArgs e)
    {
        if (con.State == ConnectionState.Open)  //apa maksudnya?
        {
            con.Close();
        }
        con.Open();
        display();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Employees.RegistrationPopOut RegPO = new Employees.RegistrationPopOut();
        RegPO.Show();
        display();


    }

Here is the code for RegisterPopOut 这是RegisterPopOut的代码

       private void BtnRegister_Click(object sender, EventArgs e)
    {
        if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "" || comboBox1.Text == "" || comboBox2.Text == "" || comboBox3.Text == "")
        {

            MessageBox.Show("Please fill in every fields");
        }
        else
        {
            int i = 0;
            SqlCommand cmd = con.CreateCommand(); //Creates and returns a SqlCommand object associated with the SqlConnection.
            cmd.CommandType = CommandType.Text; //CommandType = Specifies how a command string is interpreted. 
            cmd.CommandText = "select * from registration where username='" + textBox3.Text + "' or idno='" + textBox2.Text + "'";
            //cmd.CommandText = "select * from registration where username='" + textBox3.Text + "'";
            cmd.ExecuteNonQuery(); //used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected. 
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            i = Convert.ToInt32(dt.Rows.Count.ToString());
            if (i == 0) //If ok nada masalah register
            {
                SqlCommand cmd1 = con.CreateCommand(); //Creates and returns a SqlCommand object associated with the SqlConnection.
                cmd1.CommandType = CommandType.Text; //CommandType = Specifies how a command string is interpreted. 
                cmd1.CommandText = "insert into registration values('" + textBox3.Text + "','" + textBox4.Text + "','" + textBox1.Text + "','" + textBox2.Text + "','" + comboBox1.Text + "','" + comboBox2.Text + "','" + comboBox3.Text + "')";
                cmd1.ExecuteNonQuery(); //used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected.

                textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; comboBox1.Text = ""; comboBox2.Text = ""; comboBox3.Text = "";

                MessageBox.Show("Successfully registered");



            }
            else //if ada masalah register
            {
                MessageBox.Show("User already registered");

            }

        }



    }

I put display(); 我把display(); in AddNewUser so that it refreshes, but i didnt work. 在AddNewUser中,使其刷新,但我没有工作。

Thank you so much! 非常感谢!

2 simple way to do this: 1 - just read it again from SQL - very good way if few persons can change it at the same time 2 - databinding - better way with big and quite stable table. 2个简单的方法:1-从SQL重新读取它-如果很少有人可以同时更改它,这是一个很好的方法2-数据绑定-具有较大且相当稳定的表的更好方法。

Don't use con.open on form load!. 不要在表单加载时使用con.open Use it before command and close after execute. 在命令前使用它,在执行后关闭。 Or even better way is using(SqlConnection connection = new SqlConnection(connectionString)) 甚至更好的方法是using(SqlConnection connection = new SqlConnection(connectionString))

Prepere some metod for reading from SQL with command as argument(and maybe some DataTable for working with readed data), instead of writing it 3 times. 准备一些方法以使用命令作为参数从SQL读取(也许可以使用一些DataTable来处理读取的数据),而不是将其写入3次。 And read about how should app like this look from behind. 并从后面了解这种应用的外观。

The way you're calling RegisterPopOut from the first form is with Show() , which lets you click on the form behind, essentially not freezing it. 从第一个表单调用RegisterPopOut的方式是使用Show() ,它使您可以单击后面的表单,基本上不会冻结它。 If you don't need this feature, try this: 如果您不需要此功能,请尝试以下操作:

RegisterPopOut regPopOut = new RegisterPopOut();
regPopOut.ShowDialog();

This pauses the form and doesn't resume until the newly created form is closed using this.Close() . 这将暂停表单,直到使用this.Close()关闭新创建的表单后,该表单才会恢复。 After the new form is closed, you should safely be able to call display() and the gridview will update 关闭新表单后,您应该可以安全地调用display() ,并且gridview将更新

So try changing this: 因此,请尝试更改此内容:

private void button2_Click(object sender, EventArgs e)
    {
        Employees.RegistrationPopOut RegPO = new Employees.RegistrationPopOut();
        RegPO.Show();
        display();
    }

to this: 对此:

private void button2_Click(object sender, EventArgs e)
    {
        Employees.RegistrationPopOut RegPO = new Employees.RegistrationPopOut();
        regPopOut.ShowDialog();
        display();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM