我有一个桌面应用程序项目。在入口页面 aDataGridView
显示数据库中的现有项目。现在,当我输入一个新项目时,我想将它直接插入到DataGridView
. 意思是,我想重新加载/刷新DataGridView
. 我的数据库在 MS Access 中。
private DataTable GetData()
{
DataTable dt = new DataTable();
//using (SqlConnection con = new SqlConnection(conn))
using (OleDbConnection con=new OleDbConnection(conn))
{
OleDbCommand cmd = new OleDbCommand("Select ID,Name from GroupDetails where comID='" + label1.Text + "'", con);
//SqlCommand cmd = new SqlCommand("Select ID,Name from GroupDetails where comID='" + label1.Text + "'", con);
con.Open();
//SqlDataAdapter ad = new SqlDataAdapter(cmd);
OleDbDataAdapter ad = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
ad.Fill(ds);
dt = ds.Tables[0];
return dt;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
//SqlConnection con = new SqlConnection(conn);
OleDbConnection con = new OleDbConnection(conn);
con.Open();
//SqlCommand cmd;
try
{
string query = "insert into GroupDetails (ID,Name) values(@ID,@Name)";
// cmd = new SqlCommand(query,con);
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("@ID",txtID.Text);
cmd.Parameters.AddWithValue("@Name",txtName.Text);
int i = cmd.ExecuteNonQuery();
if(i!=0)
{
dataGridGroup.DataSource = GetData();
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
finally
{
con.Close();
}
}
[注意:当我使用 SQL 数据库时,它工作正常。]