user2631662
user2631662

Reputation: 855

Give a column in a datagrid a variable name

I have displayed data in a DataGrid from DataSet. Now I want to insert a column from this into a SQL table. Can I give the column I need in Dataset a variable name and call it in my insert command?

Create new DataSet to hold information from the worksheet.

DataSet objDataset1 = new DataSet();

// Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(objDataset1, "XLData");

// Bind data to DataGrid control.
dgCodeDisp.ItemsSource = objDataset1.Tables[0].DefaultView;

sc.Open();

Insert Command

cmd = new SqlCommand("Insert into Table (Code, v1, v2, ID) values('" +dgCodeDisp    + "','" + v1.IsChecked.ToString() + "','" + v2.IsChecked.ToString() + "', '" + txtId.Text + "')", sc);
cmd.ExecuteNonQuery();

Upvotes: 0

Views: 80

Answers (1)

DRapp
DRapp

Reputation: 48179

Depending on the SQL (SqlServer, MySQL, etc), you should use parameterized queries, otherwise you can be wide open for sql-injection. For SQL Server it typically recognizes "@" as a parameter reference for resolution when sending the command... For clarification only I've named the parameters "@parm" so you can follow it is not talking about the ACTUAL COLUMN of the table and cause confusion.

cmd = new SqlCommand("Insert into Table (Code, v1, v2, ID) values( @parmCode, @parmV1, @parmV2, @parmID )", sc );

cmd.Parameters.Add( "@parmCode", dgCodeDisp );
cmd.Parameters.Add( "@parmV1", v1.IsChecked.ToString() );
cmd.Parameters.Add( "@parmV2", v2.IsChecked.ToString() );
cmd.Parameters.Add( "@parmID", txtId.Text );
cmd.ExecuteNonQuery();

Upvotes: 1

Related Questions