简体   繁体   中英

c# DataGridView & oledb

I've a database in MS Access.
And i'm placing the data in the database to datagridview on form load.

        string connectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + Application.StartupPath + "/Db.mdb";
        OleDbConnection conObj = new OleDbConnection(connectionString);
        conObj.Open();
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        ds.Tables.Add(dt);
        OleDbDataAdapter da = new OleDbDataAdapter();
        da = new OleDbDataAdapter("SELECT * FROM StopMaster", conObj);
        da.Fill(dt);
        dataGridView1.DataSource = dt.DefaultView;
        conObj.Close();

on execution, it'll show datagridview with the items in the database,
along with an empty row where we can add new data and if we click on the existing row's items with data we can update it and even remove it

how to code for that update delete and add and reflect to the database is there any event or what
also how can i make data grid view columns not resizable.

also say if i have two columns "name" and "pin code" in the datagridview when i click on column header say for now "pin code"it must sort the datagridview rows in order
is there any event and how to for that too

The first thing to mention, is that you will need to Bind your data table to the Datagridview. This is so that any changes you make whilst editing the DataGridView control reflect directly through to the underlying DataTable.

I'll assume that you have already populated the DataTable object.

You start by creating BindingSource object :-

BindingSource bs = new BindingSource();

bs.Datasource = dt;

Now we need to make this Binding Object the datasource for your DataGridView Control :-

dataGridView1.DataSource = bs;

In a method, you can use the following code to commit changes :-

using (OleDbConnection con = new OleDbConnection(connectionString))
                {
                    var adaptor = new OleDbDataAdapter();
                    adaptor.SelectCommand = new OleDbCommand(""SELECT * FROM [StopMaster]", con);

                var cbr = new OleDbCommandBuilder(adaptor);

                cbr.GetDeleteCommand();
                cbr.GetInsertCommand();
                cbr.GetUpdateCommand();

                try
                {
                    con.Open();
                    adaptor.Update(dt);
                }
                catch (OleDbException ex)
                {
                    MessageBox.Show(ex.Message, "OledbException Error");
                }
                catch (Exception x)
                {
                    MessageBox.Show(x.Message, "Exception Error");
                }
            }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM