如何将新添加的数据行从datagridview插入数据库?

时间:2012-08-08 02:05:09

标签: c# database datagridview

我有一个datagridview,以及表中的一些数据。 datagridview允许用户输入新的数据行

问题:

我想知道如何在不添加现有数据的情况下将新插入的数据行(无论已添加多少行)添加到数据库中。

任何?

编辑:即时通讯使用sql数据库,这是我的datagridview。

enter image description here

显示的数据已经在数据库中,现在,如果用户将新的多行数据插入datagridview,该怎么办?我应该放什么代码?

我的代码如下:

private void button1_Click(object sender, EventArgs e)
        {
            con = new System.Data.SqlClient.SqlConnection();
            con.ConnectionString = "Data Source=tcp:SHEN-PC,49172\\SQLEXPRESS;Initial Catalog=LSEStock;Integrated Security=True";
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter();

            for (int i = 0; i<dataGridView1.Rows.Count; i++ )
            {

                String insertData = "INSERT INTO CostList(SupplierName, CostPrice, PartsID) VALUES (@SupplierName, @CostPrice, @PartsID)" ;
                SqlCommand cmd = new SqlCommand(insertData, con);
                cmd.Parameters.AddWithValue("@SupplierName", dataGridView1.Rows[i].Cells[0].Value);
                cmd.Parameters.AddWithValue("@CostPrice", dataGridView1.Rows[i].Cells[1].Value);
                cmd.Parameters.AddWithValue("@PartsID", textBox1.Text);
                da.InsertCommand = cmd;
                cmd.ExecuteNonQuery();
            }

            con.Close();

4 个答案:

答案 0 :(得分:1)

继承我的插入,取消和删除声明:

    protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            if (e.CommandName == "Insert") //- this is needed to explain that the INSERT command will only work when INSERT is clicked
            {
                gv.DataBind();

                DataTable d = dbcon.GetDataTable("SELECT * FROM CIS.CIS_TRANS ORDER BY ID DESC", "ProjectCISConnectionString");

                string transCode = "", fundCode = "", BSA_CD = "", DP_TYPE = "";

                if (d.Rows.Count > 0)
                {
                    transCode = d.Rows[0]["TRANS_CD"].ToString();
                    fundCode = d.Rows[0]["FUND_CD"].ToString();
                    BSA_CD = d.Rows[0]["BSA_CD"].ToString();
                    DP_TYPE = d.Rows[0]["DP_TYPE"].ToString();

                    if (transCode.Trim().Length > 0)
                    {
                        dbcon.Execute("INSERT INTO CIS.CIS_TRANS (ID,TRANS_CD) VALUES(CIS.S_CIS_TRANS.nextval,'')", "ProjectCISConnectionString");

                        gv.DataBind();
                    }
                }
gv.EditIndex = gv.Rows.Count - 1;

        }
        else if (e.CommandName == "Cancel")
        {
            DataTable d = dbcon.GetDataTable("SELECT * FROM CIS.CIS_TRANS ORDER BY ID DESC", "ProjectCISConnectionString");

            string transCode = "";

            if (d.Rows.Count > 0)
            {
                transCode = d.Rows[0]["TRANS_CD"].ToString();

                if (transCode.Trim().Length == 0)
                {
                    dbcon.Execute(string.Format("DELETE CIS.CIS_TRANS WHERE ID = '{0}'", d.Rows[0]["ID"]), "ProjectCISConnectionString");

                    gv.DataBind();
                }
            }

答案 1 :(得分:1)

您是否声明了sqlcommandbuilder,dataAdapter和dataTable?

例如:

SQLConnection con = (your connection);
SQLDataAdapter = sda;
SQLCommandBuilder = scb;
DataTable = dt;
private void btnEnter_Click(object sender, EventArgs e)


da = new SqlDataAdapter("SELECT * FROM [table] WHERE [columnA]='" + txtData.Text + "' OR [columnB]='" + txtData.Text + "' OR [ColumnC]='" + txtData.Text + "' OR [ColumnD]='" + txtData.Text + "'", con);
            ds = new DataSet();
            dt = new DataTable();
            ds.Clear();
            da.Fill(dt);
            dg.DataSource = dt;

            con.Open();
            con.Close();

private void btnUpdate_Click(object sender, EventArgs e)
    {
        //when button is clicked, the SQL Database gets updated with the data that is plugged into the datagridview.
        scb = new SqlCommandBuilder(da);
        da.Update(dt);

    }

答案 2 :(得分:0)

你有什么样的数据库?这是我的oracle数据库的源代码。如果它的SQL数据库替换为:with @。

源代码:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ProjectCISConnectionString %>" ProviderName="<%$ConnectionStrings:ProjectCISConnectionString.ProviderName %>"
            SelectCommand="SELECT * FROM CIS.CIS_TRANS ORDER BY ID ASC" 
            DeleteCommand="DELETE FROM CIS.CIS_TRANS WHERE ID = :ID"
            InsertCommand="INSERT INTO CIS.CIS_TRANS (TRANS_CD,FUND_CD,BSA_CD,DP_TYPE,TRANS_CD_DESC) VALUES (:TRANS_CD,:FUND_CD,:BSA_CD,:DP_TYPE,:TRANS_CD_DESC)"
            UpdateCommand="UPDATE CIS.CIS_TRANS SET TRANS_CD = :TRANS_CD, FUND_CD = :FUND_CD, BSA_CD = :BSA_CD, DP_TYPE = :DP_TYPE, TRANS_CD_DESC =:TRANS_CD_DESC WHERE ID = :ID">

        </asp:SqlDataSource>

您还需要查询页面和其他一些内容,请告诉我更多信息。

答案 3 :(得分:0)

我这样做。快速简单,似乎工作正常:

cmd1.Connection = this.sqlConnection1;
this.sqlConnection1.Open();

 foreach (GridViewRow row in your_grid.Rows)
        {
            Label id = (Label)row.FindControl("your_control"); //what ever control you are using

            SqlCommand cmd1 = new SqlCommand();

            cmd1.CommandText = "insert into your_table values (@p,@p1,@p2)";

            cmd1.Parameters.Add("@p", SqlDbType.VarChar).Value = your_control.Text;
            cmd1.Parameters.Add("@p1", SqlDbType.VarChar).Value = your_control.Text;
            cmd1.Parameters.Add("@p2", SqlDbType.VarChar).Value = your_control.Text;


            cmd1.CommandType = CommandType.Text;


            cmd1.ExecuteNonQuery();

        }
            this.sqlConnection1.Close();