我有一個桌面應用程序項目。在入口頁面中,datagridview顯示數據庫中的現有項目。現在,當我輸入新項目時,我想直接在datagridview中插入它。這意味着我想重新加載/刷新datagridview。我的數據庫在MS Access中。如何在.net表單應用程序和數據庫中插入或更新數據時訪問Datagridview數據?
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數據庫,然後正常工作]
可能重複的[爲什麼不datagridview刷新?](http://stackoverflow.com/questions/4108006/why-doesnt-datagridview-refresh) –