C#C
C#3y ago
Kasumi

Update DataGridView in Winforms doesnt work

Hello, I'm trying since yesterday to Update the DataGridView in my project after a Button was clicked but the issue is it doesnt even update anything.

Code:

        private void button1_Click(object sender, EventArgs e)
        {
            // Check if firstNameBox, lastNameBox and phoneBox is defined
            if(String.IsNullOrEmpty(this.firstNameBox.Text.ToString()) || String.IsNullOrEmpty(this.lastNameBox.Text.ToString()) || String.IsNullOrEmpty(this.phoneTextBox.Text.ToString()))
            {
                // Send error Message
            } else
            {
                // Create the Database Connection
                SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Student\\source\\repos\\WindowsFormsApp2\\WindowsFormsApp2\\Database.mdf;Integrated Security=True;Connect Timeout=30");
                con.Open();
                int combBox = this.comboBox1.SelectedIndex + 1;
                SqlCommand insertPatient = new SqlCommand("INSERT INTO patients (phone, firstname, lastname, address_ID) VALUES (@phoneNumb, @firstname, @lastname , "+combBox+")", con);
                insertPatient.Parameters.AddWithValue("@phoneNumb", this.phoneTextBox.Text);
                insertPatient.Parameters.AddWithValue("@firstname", this.firstNameBox.Text);
                insertPatient.Parameters.AddWithValue("@lastname", this.firstNameBox.Text);
                Console.WriteLine(this.comboBox1.SelectedIndex);
                int i = insertPatient.ExecuteNonQuery();
                con.Close();
                dataGridView1.DataSource = this.databaseData.patients;
                dataGridView1.Refresh();
                dataGridView1.Update();
            }
        }
image.png
image.png
Was this page helpful?