Обновление datagridview из другой формы в C # - PullRequest
0 голосов
/ 23 января 2019

Короче, я попробовал решения из другого поста, но не могу заставить его работать.Я новичок в программировании, и мне дали задание из моей работы по созданию программного обеспечения.

Я создал две формы, в которой первая форма называется AddNewUser, а другая - RegistrationPopOut, где последняя форма будетвсплывающее окно, если пользователь нажал «Зарегистрироваться» в форме AddNewUser.

Я хочу, чтобы представление данных в AddNewUser автоматически обновлялось само по себе при нажатии «save» на RegistrationPopOut

Вот код для 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();


    }

Вот код для 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");

            }

        }



    }

Я поставил display ();в AddNewUser, чтобы он обновлялся, но я не работал.

Большое спасибо!

Ответы [ 2 ]

0 голосов
/ 23 января 2019

То, как вы звоните RegisterPopOut из первой формы, происходит с Show(), что позволяет вам щелкнуть по форме позади, практически не замораживая ее.Если вам не нужна эта функция, попробуйте следующее:

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

Это приостанавливает форму и не возобновляется до тех пор, пока вновь созданная форма не будет закрыта с помощью this.Close().После закрытия новой формы вы сможете безопасно позвонить display(), и просмотр сетки обновится

. Попробуйте изменить это:

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

на следующее:

private void button2_Click(object sender, EventArgs e)
    {
        Employees.RegistrationPopOut RegPO = new Employees.RegistrationPopOut();
        regPopOut.ShowDialog();
        display();
    }
0 голосов
/ 23 января 2019

2 простой способ сделать это: 1 - просто прочитать его снова из SQL - очень хороший способ, если мало кто может изменить его одновременно 2 - привязка данных - лучший способ с большой и довольно стабильной таблицей.

Не используйте con.open при загрузке формы !.Используйте его перед командой и закройте после выполнения.Или, что еще лучше, using(SqlConnection connection = new SqlConnection(connectionString))

Подготовьте какой-нибудь метод для чтения из SQL с командой в качестве аргумента (и, возможно, какой-нибудь DataTable для работы с прочитанными данными) вместо записи 3 раза.И прочитайте о том, как приложение должно выглядеть так сзади.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...