Reputation: 167
I have 2 tables namely Pending.dbo
and Approved.dbo
. I have used tabcontrol. The first tab contains "Pending datagridview"
with checkbox
and btnApprove
. The second tab named "Approved"
is just a read-only datagridview.
What I want is that when I click btnApprove
, the data selected by checkbox
in "Pending datagridview"
will transfer to the table Approved.dbo
.
Is it possible? As of now, this is my codes:
language: c#
private void btnApproved_Click(object sender, EventArgs e)
{
//List<DataGridViewRow> selectedRows = (from row in dataGridView1.Rows.Cast<DataGridViewRow>() where Convert.ToBoolean(row.Cells["checkBoxColumn"].Value) == true select row).ToList();
foreach (DataGridView row in dataGridView1.Rows)
{
using (var connect = sqlcon.getConnection())
{
using (SqlCommand cmd = new SqlCommand("COMMAND TO TRANSFER DATA??????"))
{
}
}
}
}
PS. Sorry for my bad english and explanation. Thanks!
Upvotes: 2
Views: 1218
Reputation: 4445
It should be done something like this :-
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for(int i = 0; i < dataGridView1.Rows.Count; i++)
{
StrQuery = @"INSERT INTO tableName VALUES ("
+ pendingdataGridView.Rows[i].Cells["ColumnName"].Value +", "
+ pendingdataGridView.Rows[i].Cells["ColumnName"].Value +");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
If you only want to transfer selected rows to database then replace for loop part with
for(int i = 0; i < pendingdataGridView.Rows.Count; i++)
{
if(!pendingdataGridView.Rows.Selected[i])
Continue;
StrQuery= @"INSERT INTO tableName VALUES ("
+ pendingdataGridView.Rows[i].Cells["ColumnName"].Value +", "
+ pendingdataGridView.Rows[i].Cells["ColumnName"].Value +");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
and then for binding values from database to Approvedgridview
SqlDataAdapter dataAdapter = new SqlDataAdapter(selectCommand, connectionString);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
// Populate a new data table and bind it to the BindingSource.
DataTable table = new DataTable();
dataAdapter.Fill(table);
Approvedgridview.DataSource = table;
selectCommand
: query for retrieving values from database
connectionString
: your database connection string
Upvotes: 2