c#把DataGridView变成DataTable

学习目标:c#把DataGridView变成DataTable

DataTable就是内存中的一张表,dgv和dt的转换是常见的。

学习内容:

`提示:欢迎大佬踊跃发言

例如:
1,自己在winform上添加一个 DGV
在这里插在这里插入图片描述
入图片描述
2,创建 DataTable 实例

DataTable dataTable = new DataTable();

3,添加 DataTable 的列对象,即标题行,和每一列的类型(要与DGV对应,不然报格式错误)。

            dataTable.Columns.Add("ID", typeof(Int32));
            dataTable.Columns.Add("UserName", typeof(string));
            dataTable.Columns.Add("UserPassword", typeof(string));
            dataTable.Columns.Add("UserLevel", typeof(string));
            dataTable.Columns.Add("Enabled", typeof(Boolean));

4,遍历DGV的行集合,得到每一行DataGridViewRow类,这个类自带索引,可以根据列标题的name名索引,然后赋值给DT的行。

            foreach (DataGridViewRow dataGRow in DataGridView1.Rows)
            {
                DataRow dataRow = dataTable.NewRow();
                dataRow["ID"] = dataGRow.Cells["ID"].Value;
                dataRow["UserName"] = dataGRow.Cells["UserName"].Value;
                dataRow["UserPassword"] = dataGRow.Cells["UserPassword"].Value;
                dataRow["UserLevel"] = dataGRow.Cells["UserLevel"].Value;
                dataRow["Enabled"] = dataGRow.Cells["Enabled"].Value;
                dataTable.Rows.Add(dataGRow); //DT添加每一行
            }
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值