简体   繁体   中英

How to insert Data into a Database c#?

How To Take The Data From The Input boxes and insert it into the Database using the dataset?

This is what I have right Now in the Data Service Class:

public void Update(DataTable dt)
    {

        try
        {
            da = new OleDbDataAdapter("Select * from [" + dt.TableName + "]", cn);
            cn.Open();
            OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
            cb.QuotePrefix = "[";
            cb.QuoteSuffix = "]";



            da.Update(dt);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            cn.Close();
        }

    }

And this is the Button Click

 private void btnInsert_Click(object sender, EventArgs e)
        {
            try
            {
                    //dc = DataService Class
                    //ds = DataSet From DataService Class
                dc.Update(ds.Tables["Customers"]);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

Is is Possible to Insert on da.Update? This works Fine when you Edit in the DataGridView and Then Click the btninsert it gets inserted. How would I take input from Textboxes and insert it into the Database?

Question is bit unclear , but, if you want to take input from textboxes in gridview then you can simply write following code:

val1=dataGridView1.CurrentRow.Cells["Column name"].Value.ToString();

Or

val1=dataGridView1.CurrentRow.Cells[Column index].Value.ToString();

(Note: i will always recomend you first line of code)

Then simply create command object and fire insert command to insert each value in database.

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