简体   繁体   中英

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.

I want the datagridview in AddNewUser automatically updated itself if "save" is clicked on RegistrationPopOut

Here is the code for 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

       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(); in AddNewUser so that it refreshes, but i didnt work.

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.

Don't use con.open on form load!. Use it before command and close after execute. Or even better way is 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. 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. 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() . After the new form is closed, you should safely be able to call display() and the gridview will update

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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