Как обновить dataGridView в C#, не закрывая форму?
Здравствуйте!
Если кто сталкивался с этим, подскажите, как обновить dataGridView
, не закрывая форму. Вот код программы. Пользователь вводит название в текстовое поле, нажимает кнопку Browse и выбирате изображение. Нажимает кнопку Add и все это добавляет в базу данных. Чтобы отобразились данные в dataGridView
, нужно сперва закрыть форму, затем открыть. Как сделать так, чтобы форму не закрывать, а нажать на кнопку Refresh и данные, только что введенные, отобразились в dataGridView
. dataGridView1.Refresh()
и dataGridView1.Update()
не обновляют данные. Подскажите.
Вот код:
public partial class Form1 : Form {
string pathImageBrand = string.Empty;
public Form1() {
InitializeComponent();
}
//кнопка Browse
private void button1_Click(object sender, EventArgs e) {
openFileDialog1.Filter = "Images (*.jpg; *.jpeg; *.gif; *.bmp; *.ico; *.png) | *.jpg; *.jpeg; *.gif; *.bmp; *.ico; *.png";
if(openFileDialog1.ShowDialog() == DialogResult.OK) {
pathImageBrand = openFileDialog1.FileName.ToString();
}
}
//кнопка Add
private void button2_Click(object sender, EventArgs e) {
string stringConnect = @"server=localhost;user id=root;password=12345;database=abc";
string sql = "INSERT INTO avto VALUES('"+textBox1.Text+"', @imgBrands)";
byte[] imgBrands = null;
FileStream fsBrand = new FileStream(pathImageBrand, FileMode.Open, FileAccess.Read);
BinaryReader brBrand = new BinaryReader(fsBrand);
imgBrands = brBrand.ReadBytes((int)fsBrand.Length);
using(MySqlConnection connect = new MySqlConnection(stringConnect)) {
connect.Open();
MySqlCommand command = new MySqlCommand(sql, connect);
command.Parameters.Add(new MySqlParameter("@imgBrands", imgBrands));
int x = command.ExecuteNonQuery();
MessageBox.Show(x.ToString() + "record(s) saved");
}
textBox1.Clear();
}
//кнопка Refresh
private void button3_Click(object sender, EventArgs e) {
//обновить таблицу не закрывая, а затем открывая форму
//dataGridView1.Update();
dataGridView1.Refresh();
}
private void Form1_Load(object sender, EventArgs e) {
// TODO: This line of code loads data into the 'abcDataSet.avto' table. You can move, or remove it, as needed.
this.avtoTableAdapter.Fill(this.abcDataSet.avto);
}
}