I have a desktop application project. On the entry page a DataGridView
shows the existing items in the database. Now when I enter a new Item I want to insert it directly into the DataGridView
. Meaning, I want to reload/refresh the DataGridView
. My database is in 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();
}
}
[Note: When I use a SQL database then it works fine.]
i'm going to be a bit obvios but u said: "let I have to enter 5 data. ID's are 1,2,3,4,5. When I insert 1, it does not take any thing. When I entered 2 it shows 1's data. when i insert 3 it shows 2's data. That means it working from 2nd time."
and i say: when you see a behavior like that immediately know that it's a TIMING PROBLEM .
in this specific case i think that if you close your connection first then call GetData()
it should work:
private void btnSave_Click(object sender, EventArgs e)
{
//SqlConnection con = new SqlConnection(conn);
OleDbConnection con = new OleDbConnection(conn);
int i = 0;
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);
i = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
ex.Message.ToString();
}
finally
{
con.Close();
if(i!=0)
{
dataGridGroup.DataSource = GetData();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.