简体   繁体   English

如何将数据插入数据库C#?

[英]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? 是否可以在da.Update上插入? This works Fine when you Edit in the DataGridView and Then Click the btninsert it gets inserted. 当您在DataGridView中进行编辑,然后单击要插入的btninsert时,此方法工作正常。 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: 问题尚不清楚,但是,如果您想从gridview的文本框中获取输入,则只需编写以下代码即可:

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. 然后只需创建命令对象并触发插入命令即可将每个值插入数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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