简体   繁体   English

如何仅将选定的行数据从 datagridview c# 插入到 sql

[英]how to insert only selected rows data from datagridview c# to sql

i have problem with my code where i try to insert selected rows data from a datagridview to sql database, but it only works for one row, even im using a loop for every selected row, i get the violation of primary key of one inserted row of those multiple rows and then it stops and cancel the rest, even that these rows has not the same primary key我的代码有问题,我尝试将选定的行数据从 datagridview 插入到 sql 数据库,但它只适用于一行,即使我对每个选定的行使用一个循环,我也违反了一个插入行的主键这些多行然后它停止并取消 rest,即使这些行没有相同的主键

its like the loop goes multiple times on the same row i'm not really sure whats happening im really stuck!它就像循环在同一行多次运行我不太确定发生了什么我真的卡住了!

what i want is when i select multiple rows in datagridview and clicking a bouton these line are saved(i hope i get only a small edit and not the whole code changes)我想要的是当我 select datagridview 中的多行并单击这些行时,这些行被保存(我希望我只得到一个小的编辑而不是整个代码更改)

foreach (DataGridViewRow row in dataGridView1.SelectedRows)
        {
                //i tried all these
                //int index = dataGridView1.CurrentRow.Index
                //int index = datagridview.CurrentCell.RowIndex
                int index = dataGridView1.SelectedRows[0].Index;
                d.cmd.CommandText = "insert into projection values('" +
                            d.dt.Rows[index][0].ToString() +
                    "','" + d.dt.Rows[index][1].ToString() +
                    "','" + d.dt.Rows[index][2].ToString() +
                    "','" + d.dt.Rows[index][3].ToString() +
                    "','" + d.dt.Rows[index][4].ToString() +
                    "','" + d.dt.Rows[index][5].ToString() +
                    "','" + d.dt.Rows[index][6].ToString() +
                    "')";
                d.cmd.Connection = d.con;
                d.cmd.ExecuteNonQuery();
        }

For starters, you need to use parameters.对于初学者,您需要使用参数。 Second, you are doing a foreach on each selected row already.其次,您已经在每个选定的行上执行 foreach。 Access the data in each cell with: row.Cells[columnNumber].Value访问每个单元格中的数据: row.Cells[columnNumber].Value

First off, setup the DataGridView with a DataSource, like a DataTable.首先,使用 DataSource 设置 DataGridView,例如 DataTable。 Then perhaps in a Button Click event get the selected rows.然后也许在 Button Click 事件中获取选定的行。

private void InsertButton_Click(object sender, EventArgs e)
{
    if (dataGridView1.SelectedRows.Count == 0) return;

    List<DataRow> selectedRows = dataGridView1
        .SelectedRows
        .Cast<DataGridViewRow>()
        .Select(dgvr => ((DataRowView)dgvr.DataBoundItem).Row)
        .ToList();

    var (success, exception) = Operations.Insert(selectedRows);
    if (success)
    {
        // rows inserted
    }
    else
    {
        // exception has info for failure
    }

}

Place your data operations in a class. Here two columns are used.把你的数据操作放在一个class里面,这里用到了两列。 You would add a column for each column in the DataGridView.您将为 DataGridView 中的每一列添加一列。 And you need to change the data provider if not using SQL-Server.如果不使用 SQL-Server,则需要更改数据提供程序。

public class Operations
{

    private static string _connectionString = "TODO";

    public static (bool success, Exception exception) Insert(List<DataRow> rows)
    {
        using (var cn = new SqlConnection() { ConnectionString = _connectionString })
        {
            using (var cmd = new SqlCommand() { Connection = cn })
            {
                cmd.CommandText = "INSERT INTO Customers VALUES (@CompanyName, @ContactId)";
                cmd.Parameters.Add("@CompanyName", SqlDbType.NVarChar);
                cmd.Parameters.Add("@ContactId", SqlDbType.Int);

                try
                {
                    cn.Open();

                    foreach (var row in rows)
                    {
                        cmd.Parameters["@CompanyName"].Value = row.Field<string>("CompanyName");
                        cmd.Parameters["@ContactId"].Value = row.Field<int>("ContactId");
                        cmd.ExecuteNonQuery();
                    }

                    return (true, null);
                }
                catch (Exception localException)
                {
                    return (false, localException);
                }
            }
        }
    }
}

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

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