日期:2014-05-20  浏览次数:21067 次

datagridview 保存数据
用   datagridview   控件怎么把写入的数据保存到数据库中去?


------解决方案--------------------
以前用2003写的仅供参考
private void SubmitChanges()
{
if (dsOneToMany.HasChanges())
{
conn.Open();
SqlTransaction txn = conn.BeginTransaction();
adpOrders.UpdateCommand.Transaction = txn;
adpOrders.InsertCommand.Transaction = txn;
adpOrders.DeleteCommand.Transaction = txn;
adpDetails.UpdateCommand.Transaction = txn;
adpDetails.InsertCommand.Transaction = txn;
adpDetails.DeleteCommand.Transaction = txn;

try
{
int intOrdersModified, intDetailsModified;
intOrdersModified = adpOrders.Update(dsOneToMany.Orders.Select( " ", " ", DataViewRowState.Added | DataViewRowState.ModifiedCurrent));
intDetailsModified = adpDetails.Update(dsOneToMany.Order_Details);

intOrdersModified += adpOrders.Update(dsOneToMany.Orders.Select( " ", " ", DataViewRowState.Deleted));

txn.Commit();
MoveFirst();

string strOutput = "已修改 " + intOrdersModified + " 条订单信息\r\n " +
"已修改 " + intDetailsModified + " 条订单明细信息 ";
MessageBox.Show(strOutput, "更新成功 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "更新失败 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
txn.Rollback();
}
finally
{
conn.Close();
}
}
}
------解决方案--------------------
private DataTable DataGridToDataTable(DataGridView dgList)
{
DataTable newdt = new DataTable();
try
{
DataTable dt2 = (DataTable)dgList.DataSource;
int colCount = dgList.Columns.GetColumnCount(DataGridViewElementStates.Visible);
string[] ColumnNames = new string[colCount];
int j = 0;
for (int i = 0; i < dgList.Columns.Count; i++)
{
if (dgList.Columns[i].Visible)
{
ColumnNames[j] = dgList.Columns[i].Name.ToString();
j++;
}
}

foreach (string ColumnName in ColumnNames)
{
newdt.Columns.Add(ColumnName);
}

for (int i = 0; i < dt2.Rows.Count; i++)
{
DataRow drNew = newdt.NewRow();
foreach (string ColumnName in ColumnNames)
{
drNew[ColumnName] = dt2.Rows[i][ColumnName];
}
newdt.Rows.Add(drNew);
newdt.AcceptChanges();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return newdt;

}

DataTable dt = this.DataGridToDataTable(dgList);
SqlDataAdapter + SqlCommandBuilder ..

调用SqlDataAdapter.Update(DataTable);