ADO.NET中DataTable的应用

DataTable的应用,其实上周博客已经说了更新的查询,这周要讲的是创建新列和数据在两张DataTable表之间的移动
这里我定义了两张表,一张表保存从数据库中读出的数据,另一张表刚开始是空表,只有从第一张表读来的格式

private DataTable Table;  
private DataTable SDrug; 

this.SDrug = Table.Clone(); //SDrug表复制Table表的格式

ADO.NET中DataTable的应用

图中可以看出,SDrug只有Table表的格式,但相比于Table表,还多了**“数量”列和“金额”列,新增列有很多种方式,比如说“数量”**列的代码如下

SDrug.Columns.Add("数量", typeof(string));

**“金额”**列的代码如下

DataColumn txt_je = new DataColumn();
txt_je.ColumnName = “金额”;
txt_je.DefaultValue = 0; //默认值
SDrug.Columns.Add(txt_je);
this.dgv_SelectDrug.Columns[“金额”].ReadOnly = true;

由于功能的需要,**“金额”**列的值是“数量”*“单价”,需要操作系统自动给出结果,代码如下

this.dgv_SelectDrug.Rows[i].Cells["金额"].Value =(Convert.ToSingle(this.dgv_SelectDrug.Rows[i].Cells["单价"].Value ) * Convert.ToSingle(this.dgv_SelectDrug.Rows[i].Cells["数量"].Value )).ToString ();   //i代表行数

接下来是数据在表之间的移动,把Table表中的数据添加到SDrug表的代码如下

if (this.dgv_Drug.RowCount > 0) //若有选中
{
DataRow currentCourseRow = ((DataRowView)this.dgv_Drug.CurrentRow.DataBoundItem).Row , selectedCourseRow = this.SDrug.NewRow();
selectedCourseRow[0] = currentCourseRow[0];
selectedCourseRow[1] = currentCourseRow[1];
selectedCourseRow[3] = currentCourseRow[3];
selectedCourseRow[5] = currentCourseRow[5];
this.SDrug.Rows.Add(selectedCourseRow);
currentCourseRow.Delete();

    }

其中 0,1,3,5是表中未隐藏数据的位置,可以根据自己的需求更改

把SDrug表的数据还回Table表的代码如下

 if (this.dgv_SelectDrug.RowCount > 0)                                                    
            {
                DataRow SelectDrug =                                                              
                    ((DataRowView)this.dgv_SelectDrug.CurrentRow.DataBoundItem).Row;                 
                if (SelectDrug.RowState == DataRowState.Added)                                     
                    string courseNo = SelectDrug["ypbh"].ToString();                                  
                    DataRow deletedCourseRow =                                                              
                        this.Table.Select("ypbh='" + courseNo + "'", "", DataViewRowState.Deleted)[0]; 
                    deletedCourseRow.RejectChanges();                                                       
                    this.SDrug.Rows.Remove(SelectDrug);                            
                    
                }
            }

可以发现,移动时其实就是隐藏Table表中的选定列,复制给SDrug表并输出;返还时其实就是删除SDrug表的被选中列,把Table表中对应的列取消隐藏
程序的运行结果如下

ADO.NET中DataTable的应用

然后使用上周的添加功能就能完成提交了
ADO.NET中DataTable的应用

ADO.NET中DataTable的应用