简体   繁体   中英

Refresh DataGridView after inserting values

I have established connection and inserted values into the table.

However, I am not sure the best method to refresh the DataGridview as the values have been inserted after click button.

private void button1_Click(object sender, EventArgs e)
{           
   {             
      string theText = makeTextBox.Text;
      string theText2 = modelTextBox.Text;
                
      var value = Convert.ToInt32(yearTextBox.Text);      
      int i = 6;
      cnn.Open();
      MySqlCommand cmd = new MySqlCommand();
      cmd.Connection = cnn;
      cmd.CommandText = "INSERT INTO cars(Make,Model,Year) VALUES(@Make,@Model,@Year)";
      cmd.Prepare();

      cmd.Parameters.AddWithValue("@Make", theText);
      cmd.Parameters.AddWithValue("@Model", theText2);
      cmd.Parameters.AddWithValue("@Year", value);
                
      cmd.ExecuteNonQuery();
   {
}

      dataGridView1.DataSource = carsBindingSource;
      dataGridView1.Refresh();

      cnn.Close();

            }
        }
    }
    }

enter image description here

EDIT:

here is the code with the working solution of rebinding the datasource and then it will update:

        {
            string theText = textBox1.Text;
            string theText2 = textBox2.Text;

            var value = Convert.ToInt32(textBox3.Text);

            int i = 6;
            cnn.Open();
            MySqlCommand cmd = new MySqlCommand();
            cmd.Connection = cnn;
            cmd.CommandText = "INSERT INTO cars(Make,Model,Year) VALUES(@Make,@Model,@Year)";
            cmd.Prepare();

            cmd.Parameters.AddWithValue("@Make", theText);
            cmd.Parameters.AddWithValue("@Model", theText2);
            cmd.Parameters.AddWithValue("@Year", value);

            cmd.ExecuteNonQuery();
            {
            }








            cnn.Close();

            carsBindingSource = new BindingSource();
            carsBindingSource.DataSource = carsTableAdapter.GetData();
            dataGridView2.DataSource = carsBindingSource;
        }
    }```

I dont think its possible. You may need to create a separate button to submit and then refresh the data

Your code is missing the part where the carsBindingSource variable is initialized with data. From your limited code, it should be noted that… if you add/insert a new row into the table in the data base, then this is NOT going to automatically update the carsBindingSource.

It is unknown “what” is used as a DataSource to the carsBindingSource. OR, how this data source is populated. I will assume the DataSource to the BindingSource is a DataTable and that somewhere in the code it is getting this DataTable from a query to the data base. If this process is not already in a single method that returns a DataTable , then, I recommend you create one, and it may look something like…

private DataTable GetCarsDT() {
  DataSet ds = new DataSet();
  string connString = "Server = localhost; Database = CarsDB; Trusted_Connection = True;";
  try {
    using (SqlConnection conn = new SqlConnection(connString)) {
      conn.Open();
      using (SqlCommand command = new SqlCommand()) {
        command.Connection = conn;
        command.CommandText = "SELECT * FROM Cars";
        using (SqlDataAdapter da = new SqlDataAdapter(command)) {
          da.Fill(ds, "Cars");
          return ds.Tables[0];
        }
      }
    }
  }
  catch (Exception ex) {
    MessageBox.Show("DBError:" + ex.Message);
  }
  return null;
}

Above will return a DataTable with three (3) columns, Make, Model and Year. This DataTable is used as a DataSource to the BindingSourcecarsBindingBource.

Now in the button1_Click event, the code inserts the new values into the data base. However, the carsBindingSource will still contain the data “before” the new items were added to the DB. Therefore, we can simply use the method above to “update” the carsBindingSource after the new items are added to the DB.

Note: you can go two routs here, 1) as described above, simply update “all” the data in the binding source… OR … 2) after updating the new items into the data base, you can also add the new items to the binding source's data source… ie its DataTable . Either way will work and unless there is a large amount of data, I do not think one way would be preferred over the other.

Below shows what is described above. Note, the commented code adds the new items directly to the DataTable. You can use either one but obviously not both.

private void button1_Click(object sender, EventArgs e) {
  string connString = "Server = localhost; Database = CarsDB; Trusted_Connection = True;";
  try {
    using (SqlConnection conn = new SqlConnection(connString)) {
      conn.Open();
      using (SqlCommand command = new SqlCommand()) {
        command.Connection = conn;
        command.CommandText = "INSERT INTO cars(Make,Model,Year) VALUES(@Make,@Model,@Year)";
        command.Parameters.Add("@Make", SqlDbType.NChar, 50).Value = makeTextBox.Text.Trim();
        command.Parameters.Add("@Model", SqlDbType.NChar, 50).Value = modelTextBox.Text.Trim();
        int.TryParse(yearTextBox.Text.Trim(), out int year);
        command.Parameters.Add("@Year", SqlDbType.Int).Value = year;
        command.ExecuteNonQuery();
        carsBindingSource.DataSource = GetCarsDT();
        //DataTable dt = (DataTable)carsBindingSource.DataSource;
        //dt.Rows.Add(makeTextBox.Text.Trim(), modelTextBox.Text.Trim(), year);
      }
    }
  }
  catch (Exception ex) {
    MessageBox.Show("DBError:" + ex.Message);
  }
}

Putting all this together…

BindingSource carsBindingSource;

public Form1() {
  InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
  carsBindingSource = new BindingSource();
  carsBindingSource.DataSource = GetCarsDT();
  dataGridView1.DataSource = carsBindingSource;
}

Hope this makes sense.

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