我想在数据库表
中的每个DataGridView
之后添加刷新INSERT INTO
OleDbConnection objConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='database.accdb'");
String sqlquery = "INSERT INTO MyTable" +
"(Column1, Column2, Column3, Column4)" +
"VALUES (@Column1, @Column2, @Column3, @Column4)";
OleDbCommand objCommand = new OleDbCommand(sqlquery, objConnection);
objConnection.Open();
objCommand.Parameters.AddWithValue("@Column1", txtAccount.Text);
objCommand.Parameters.AddWithValue("@Column2", txtAccountNumber.Text);
objCommand.Parameters.AddWithValue("@Column3", txtCardNumber.Text);
objCommand.Parameters.AddWithValue("@Column4", txtDescription.Text);
objCommand.ExecuteNonQuery();
objConnection.Close();
// Now I want Refresh Data Grid View
BindingSource bindingsource = new BindingSource();
bindingsource.DataSource = this.databaseDataSet.MyTable;
dataGridView1.DataSource = bindingsource;
dataGridView1.Update();
dataGridView1.Refresh();
但它不会刷新数据网格视图。
我该如何解决?
答案 0 :(得分:1)
绑定新源时尝试此操作
dataGridView1.DataSource = null;
dataGridView1.DataSource = bindingsource;
dataGridView1.Refresh();
答案 1 :(得分:0)
您可以尝试这样做,
private void AddData()
{
if(command.ExecuteNonQuery()>0)
{
//Call your BindData method to reflect the latest records on datagridview when binding
BindData();
}
}
private void BindData()
{
//Bind your datagridview with the datasource
}
答案 2 :(得分:0)
您真的不需要刷新任何内容 - 只需将新对象添加到数据库并更新绑定源。
这是一个例子。我有一个带有dataGridView,docsBindingSource和addButton的Form。 Form1_Load - 是非常重要的部分(因为绑定)
private void Form1_Load(object sender, EventArgs e)
{
using (var db = new db())
{
// now our dataGridView will show us 'docs'
docsBindingSource.DataSource = db.docs.ToList();
}
}
// a.k.a. Insert event
private async void addBtn_Click(object sender, EventArgs e)
{
using (frmAddEdit frm = new frmAddEdit())
{
frm.ShowDialog();
// after I Show frmAddEdit Form, i will change his DialogResult
// in some period of time
if (frm.DialogResult == DialogResult.OK)
{
try
{
// then i make db object
using (var db = new db())
{
// adding data
var added = db.docs.Add(new docs()
{
docsAgent = frm.docsInfo.docsAgent,
docsStaff = frm.docsInfo.docsStaff,
docsType = frm.docsInfo.docsType
});
// saving
await db.SaveChangesAsync();
// and updating my bindingSource, which is a source for
// my dataGridView
docsBindingSource.Add(added);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw;
}
}
}
}