datatable保存mysql,如何将数据从数据表保存到数据库

DataSet ds = new DataSet();

DataTable dt = new DataTable();

dt.TableName = "MyTable";

foreach (DataGridViewColumn col in dataGridView1.Columns)

{

dt.Columns.Add(col.DataPropertyName, col.ValueType);

}

foreach (DataGridViewRow gridRow in dataGridView1.Rows)

{

if (gridRow.IsNewRow)

continue;

DataRow dtRow = dt.NewRow();

for (int i1 = 0; i1 < dataGridView1.Columns.Count; i1++)

dtRow[i1] = (gridRow.Cells[i1].Value == null ? DBNull.Value : gridRow.Cells[i1].Value);

dt.Rows.Add(dtRow);

}

ds.Tables.Add(dt);

System.Diagnostics.Debugger.Break();

This is my code and I need to insert the datatable into "MyTable" and the Columns will be dynamic,but I cant be creating columns all the time.

Please can any one tell me how to do this?

解决方案

For any given requirement, you will need to specify the column definition. This will map to the corresponding table in the database. Else how will you specify which column's value in the datatable maps to which column in the physical table?

Ideally the mapping should be 1:1 based on exact names. Like the name of datatable corresponds to the name of physical table and each column in datatable named after same column in physical table.

You can iterate over your datasource and create columns by index, but then you must be sure that the insert query takes the columns in same order as you are inserting in the datatable.

The AutoGenerateColumns property of the grid works in this way only, although in reverse order

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值