简体   繁体   中英

Insert multiple records from datagridview to SQL server database

I have a project in C# which the user can choose only one row in datagridview and fill it's data by filling textboxes, but that takes a long time to do, so how can I develop the below code that user can choose a group of names (which the same data should be recorded) by select several rows in datagridview to insert data into SQL server database? this the code I use after select a separate row:

        {
            hour.ADD_ADDITIONAL_HOURS(Convert.ToInt32(txtRecID.Text), dtDateFrom.Value.Date, dgActiveEmps.CurrentRow.Cells[0].Value.ToString(), Convert.ToInt32(cmbSymboles.SelectedValue), Convert.ToInt32(txtHours.Text));
        }

note: ADD_ADDITIONAL_HOURS is a stored procedure

The easiest way to do this is to use table valued parameters. To do this, firstly create a user defined table type in SQL Server thus:

CREATE TYPE dbo.YourTypeName AS TABLE  
(  
   [ID] [nvarchar(50)] 
)

(I am assuming that your Cells[0].value contains a string. If it is another data type, then change the type of ID above appropriately).

Next change the third parameter of your stored procedure to <parameter_name> AS dbo.YourTypeName READONLY) . Within the body of your procedure, change the update(?) statement to be based on a join with this parameter - you use it like any other table. It should look something like:

UPDATE t
SET col1 = @param1 ....
FROM YourTable t INNER JOIN @tablevaluedparameter tvp ON tvp.ID = t.ID

Turning to c#, you need to change the third parameter passed to the stored procedure to be SqlDbType.Structured . Finally you need to populate the parameter with the values from SelectedRows . Here you have a choice: the values can be placed in any of DataTable , IEnumerable<SqlDataRecord> or DbDataReader ; all of these can be the Value property of the parameter.

For example, using a DataTable your code would look something like this:

var dT = new DataTable();
dT.Columns.Add(new DataColumn("ID", typeof(string));

for (int i = 0: i < dgActiveEmps.SelectedRows.Count; i++)
{
    dT.Rows.Add(dgActiveEmps.SelectedRows[i].Cells[0].Value.ToString());
} 

yourSqlCommand.Parameters.Add(new SqlParameter
{
    ParameterName = "@tablevaluedparameter",
    SqlDbType = SqlDbType.Structured,
    Value = dT,
    TypeName = "dbo.YourTypeName"
});

Obviously you will need to adapt the namings to fit your case, but I hope it should be clear what you need to do.

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