简体   繁体   English

插入值后刷新 DataGridView

[英]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.但是,我不确定刷新 DataGridview 的最佳方法,因为在单击按钮后插入了值。

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.您的代码缺少使用数据初始化carsBindingSource变量的部分。 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.从您有限的代码中,应该注意......如果您在数据库中的表中添加/插入新行,那么这不会自动更新carsBindingSource.

It is unknown “what” is used as a DataSource to the carsBindingSource.未知“什么”用作汽车绑定DataSource的数据源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.我将假设BindingSourceDataSource是一个DataTable ,并且在代码中的某处它正在从查询到数据库中获取这个DataTable 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…如果这个过程还没有在一个返回DataTable的方法中,那么,我建议你创建一个,它可能看起来像……

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.上面将返回一个包含三 (3) 列、Make、Model 和 Year 的DataTable This DataTable is used as a DataSource to the BindingSourcecarsBindingBource.DataTable用作BindingSource ... carsBindingBource.DataSource

Now in the button1_Click event, the code inserts the new values into the data base.现在在button1_Click事件中,代码将新值插入到数据库中。 However, the carsBindingSource will still contain the data “before” the new items were added to the DB.但是, carsBindingSource仍将包含新项目添加到数据库“之前”的数据。 Therefore, we can simply use the method above to “update” the carsBindingSource after the new items are added to the DB.因此,我们可以简单地使用上述方法在新项目添加到数据库后“更新” carsBindingSource

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 .注意:这里可以 go 两个路由,1)如上所述,只需更新“所有”绑定源中的数据......或...... 2)在将新项目更新到数据库后,您还可以将新项目添加到绑定源的数据源……即它的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.请注意,注释代码将新项目直接添加到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.希望这是有道理的。

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

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