how to update or refresh datagrid view connected with Ms-access in C#

柔情痞子 提交于 2019-12-24 10:58:57

问题


hi i have already connected the database in Ms-access 2010(.mdb) with C# then i want to display it in datagrid view , here is the code that i used to save or insert the data

OleDbCommand cmd = new OleDbCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into VMS(PlateNo,JobCardNo,Model,DateIn,Status,PartList,PurchNo,PurchDate,Remark)" + "values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "','" + textBox9.Text + "')";
        cmd.Connection = mycon;
        mycon.Open();
        cmd.ExecuteNonQuery();
        mycon.Close();

this works right, the problem is when i save new data it save in MS- access but it will not updated or displayed in the datagridview. any help will be appreciated


回答1:


This is the best way To update your datagridview after inserting some data.

Dataset sDs = new DataSet();

sAdapter.Fill(sDs, "T1");

sTable = sDs.Tables["T1"];

dataGridView1.DataSource = sDs.Tables["T1"];




回答2:


To update your datagridview after inserting some data , you should rebind your data grid view , some sudocode might be like this :

OledbConnection conn=new OledbConnection("your connectionstring");
OledbCommand comm=new OledbCommand("SELECT * FROM yourtablename",conn);
OledbDataAdapter da=new OledbDataAdatpter(comm);
Dataset ds=new dataSet();
conn.open();
da.Fill(ds,"T1");
datagridView.DataMember="T1";
datagridview.DataSource=ds;
conn.close();

NOTE: if your project is an asp.net project after assigning the datasource you have to write the method DataBind() to your datagridview this way :

datagridview.DataSource=ds;
datagridview.DataBind();

but in windows applications you don't have to perform the method DataBind()

please mark as answer if you It solved your problem



来源:https://stackoverflow.com/questions/10480462/how-to-update-or-refresh-datagrid-view-connected-with-ms-access-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!