TO HOW: ??????????? DataSet ????? ????? ???? ??? ????? C# .NET

???? ?????? ???? ??????
???? ID: 326080 - ?? ???????? ?? ?????? ??? ?? ?? ???? ???? ???? ??.
??? ?? ??????? ???? | ??? ?? ??????? ????

?? ????? ??

??????

?? ??? ?? ??? ???? ????? ?? ?? ??? ?????? ?? ????? ???? ?? ??????????? ???? ?? ??? ???? ??DataSetHelperclass that includes sample code to create aDataTableobject from two or more relatedDataTabledefinitions and to copy records that are sorted and filtered from the sourceDataTableobjects to the destinationDataTable.

To do this, you use the following public methods:
  • CreateJoinTable
  • InsertJoinInto
  • SelectJoinInto
TheSelectJoinIntomethod calls theCreateJoinTable??InsertJoinInto???????? You can also use a private helper method and data members to store the parsed field list.

TheDataSetHelperclass includes aDataSetmember variable. Optionally, you can assign an existingDataSet???? ?? ???DataSetmember variable. If the member variable points to a validDataSet, anyDataTableobjects that theCreateJoinTable??SelectJoinIntomethod creates are added to theDataSet. In either case, the method call returns a reference to theDataTable???????? ??? TheInsertJoinIntomethod requires an existing targetDataTableand does not return anything.

For more information aboutDataSetobjects, click the article number below to view the article in the Microsoft Knowledge Base:
313485INFO: Roadmap for ADO.NET DataSet, DataView, and DataViewManager

??????????

The following list outlines the recommended hardware, software, network infrastructure, and service packs that are required:
  • Microsoft Windows XP, Windows 2000, or Windows NT 4.0 Service Pack 6a
  • Microsoft Visual Studio .NET
?? ???? ????? ?? ?? ?? ????? ???? ?? ?????? ???:
  • Visual C# .NET syntax
  • ADO.NET fundamentals ?? ????????

DataSetHelper ??? ????

?? ?????? ??? ??? declares ??? ???? ?? ??? ?? ???DataSetHelper?????? ??????? ?? ????? ?? ???????
  1. Visual Studio .NET ?? ??????? ?????
  2. ????? ???????????? ??,????? ????-????? ????, ?? ???? ????????????.
  3. ???????? ?????????????? ????? ???, ????? ????????? C# ??????????? ???????????????? ???????? ????-????? ????, ?? ???? ???????? ??????????? ???????????????.
  4. ????????????? ???,DataSetHelper.
  5. ???? ??? ?? ????? ??? ?? ???????????? ????:
    public class DataSetHelper
    {
        public DataSet ds;
    
        public DataSetHelper(ref DataSet DataSet)
        {
    	ds = DataSet;
        }
        public DataSetHelper()
        {
    	ds = null;
        }
    }
    					
    ???? ?? ??????? ????? ?? ??? ?? ???? ???? ????? ???? ?? ??? ??? ?????? ?? ??? ?? constructor ?? ??? ?? overloads ?? ????? ?? ???? ???DataSet. ??? ????? ???? ?? ??? ??? ?????? ??? ?? ???? ?? ???DataSet,DataTable???????? ??????? ?? ???? ???? ?? ??? ???????? ??? ?? ????? ?? ??? ???DataSet.

????? ???? ??????

?? ??? ??? ??? ????? ???? ?????? ?? ??? ??? ??? Parsed ?????? ?? ????? ???? ???? ?? ????CreateJoinTable??InsertJoinInto????? ???? reparse ???? ?? ??? ??????? ???? ??? ?? ??????? ????? ???? reparse ???? ??? ?? ?? ??? ???? ???SelectJoinInto?????? ?? ???? ??? ??? Parsed ????? ???? ?? unparsed ????? ???? ??? ???????? ???? ????????? ????? ??DataSetHelper?????
  1. ????? ????????????? ??????? ????DataSetHelper???? ??? ???? ?? ""??????:
    private class FieldInfo
    {
        public string RelationName;
        public string FieldName;	//source table field name
        public string FieldAlias;	//destination table field name
        public string Aggregate;
    }
    					
    ???:: ?? ???? ?? ??? ???? ??????? ??DataSetHelperarticles ?? ?? ?? ???? ?? ????? ???? ???? ?? ??? ????????? ??? ????

  2. ????? ??????????????? ?? ???? ?? ???????? ???? ?? ??? ?????DataSetdeclaration:
    private System.Collections.ArrayList m_FieldInfo; private string m_FieldList; 
    					
  3. ????? ?????????????? ?? ???????? ???? ?? ??? ?????? ??? ?? ???? ????? ??? ????? ???? ???? ?? ?? ???? ?? ???? ??DataSetHelper??? ???
    private void ParseFieldList(string FieldList, bool AllowRelation)
    {
        /*
         * This code parses FieldList into FieldInfo objects  and then 
         * adds them to the m_FieldInfo private member
         * 
         * FieldList systax:  [relationname.]fieldname[ alias], ...
        */ 
        if (m_FieldList == FieldList) return;
        m_FieldInfo = new System.Collections.ArrayList();
        m_FieldList = FieldList;
        FieldInfo Field; string[] FieldParts;
        string[] Fields=FieldList.Split(',');
        int i;
        for (i=0; i<=Fields.Length-1; i++)
        {
            Field=new FieldInfo();
            //parse FieldAlias
            FieldParts = Fields[i].Trim().Split(' ');
            switch (FieldParts.Length)
            {
                case 1:
                    //to be set at the end of the loop
                    break;
                case 2:
                    Field.FieldAlias=FieldParts[1];
                    break;
                default:
                    throw new Exception("Too many spaces in field definition: '" + Fields[i] + "'.");	                        
            }
            //parse FieldName and RelationName
            FieldParts = FieldParts[0].Split('.');
            switch (FieldParts.Length)
            {
                case 1: 
                    Field.FieldName=FieldParts[0];
                    break;
                case 2:
                    if (AllowRelation==false)
                        throw new Exception("Relation specifiers not permitted in field list: '" + Fields[i] + "'.");
                    Field.RelationName = FieldParts[0].Trim();
                    Field.FieldName=FieldParts[1].Trim();
                    break;
                default:
                    throw new Exception("Invalid field definition: " + Fields[i] + "'.");
            }
            if (Field.FieldAlias==null) 
                Field.FieldAlias = Field.FieldName;
            m_FieldInfo.Add (Field);
        }
    }
    					

CreateJoinTable ????

?? ??? ?? ??? ??? ??? ????? ????CreateJoinTable?????? ???

????? ?? ??? ?????? ????? ??CreateJoinTable????:
dt = dsHelper.CreateJoinTable("TestTable", ds.Tables["Employees"],
    "FirstName FName,LastName LName,DepartmentEmployee.DepartmentName Department");
				
?? ??? ????? ?? ??? ????? ??DataTable?? ??? ??TableNameTestTable ?? ??? ????????? (FName, LName ?? ?????)? ?? ??? ????????? ?? ??? ?? ???? FirstName ?? ??????????? ?? ???? ??? LastName ????? ?? DepartmentEmployee ?? ?????? ?? ?????? ?????? ?????? ??? DepartmentName ????? ?? ??? ??? ?????DataRelation???????? ???

????? ???? ??? ????? ????????? ???? ?? ??? ????? ???????? ?? ????? ????:
[relationname.]fieldname[ alias], ...
				
?? ???????? ?? ??? ????? ??? ????:
  • TheColumnName??DataTypeproperties are the only properties that are copied to the destinationDataTable.
  • The evaluated result is copied for fields that contain an expression.
  • You can rename a field in the destinationDataTableby specifying an alias name.
  • The field list can contain a subset of field names that are listed in a different order than the order in the sourceDataTable. If the field list is blank, an exception is thrown.
  • TheDataRelationmust relate to the parent tables. For example, if you want to create a table that combines fields of the Customers, the Employees, and the Orders tables, you must use the Orders table as the source table and then reference fields in the Customers and the Employees tables by means of relations.
To call theCreateJoinTablemethod, add the following method to theDataSetHelperclass that you created in the "" section:
public DataTable CreateJoinTable(string TableName, DataTable SourceTable, string FieldList)
{
    /*
     * Creates a table based on fields of another table and related parent tables
     * 
     * FieldList syntax: [relationname.]fieldname[ alias][,[relationname.]fieldname[ alias]]...
    */ 
    if (FieldList==null)
    {
        throw new ArgumentException("You must specify at least one field in the field list.");
        //return CreateTable(TableName, SourceTable);
    }
    else
    {
        DataTable dt = new DataTable(TableName);
        ParseFieldList(FieldList, true);
        foreach(FieldInfo Field in m_FieldInfo)
        {
            if(Field.RelationName==null)
            {
                DataColumn dc = SourceTable.Columns[Field.FieldName];
                dt.Columns.Add(dc.ColumnName, dc.DataType, dc.Expression);
            }
            else
            {
                DataColumn dc = SourceTable.ParentRelations[Field.RelationName].ParentTable.Columns[Field.FieldName];
                dt.Columns.Add(dc.ColumnName, dc.DataType, dc.Expression);
            }
        }
        if (ds!=null)
            ds.Tables.Add(dt);
        return dt;
    }
}
				

InsertJoinInto Method

This section contains code for theInsertJoinInto?????? ??? TheInsertJoinIntomethod copies records that are sorted and filtered from the source table and related tables to the destination table. ?? ?? ???ParseFieldListproperty, you can parse lists that were previously parsed, if these lists are available. If the field list is blank, an exception is thrown.

The following is the calling convention for theInsertJoinInto????:
dsHelper.InsertJoinInto(ds.Tables["TestTable"], ds.Tables["Employees"], 
    "FirstName FName,LastName LName,DepartmentEmployee.DepartmentName Department", 
    "EmployeeID<5", "BirthDate");
				
The call sample copies records from the EmployeesDataTable(and the DepartmentName field of a relatedDataTable) to the TestTableDataTable, which is filtered on "EmployeeID<5" and="" is="" sorted="" by=""></5">

???:: The filter and the sort expressions apply only to the source table and not to any related tables.

To call theInsertJoinIntomethod, add the following method to theDataSetHelperclass that you created in the "" section:
public void InsertJoinInto(DataTable DestTable, DataTable SourceTable, 
    string FieldList, string RowFilter, string Sort)
{
    /*
    * Copies the selected rows and columns from SourceTable and inserts them into DestTable
    * FieldList has same format as CreatejoinTable
    */ 
    if (FieldList==null)
    {
        throw new ArgumentException("You must specify at least one field in the field list.");
        //InsertInto(DestTable, SourceTable, RowFilter, Sort);
    }
    else
    {
    ParseFieldList(FieldList, true);
    DataRow[] Rows = SourceTable.Select(RowFilter, Sort);
    foreach(DataRow SourceRow in Rows)
    {
            DataRow DestRow = DestTable.NewRow();
            foreach(FieldInfo Field in m_FieldInfo)
            {
                if(Field.RelationName==null)
                {
                    DestRow[Field.FieldName] = SourceRow[Field.FieldName];
                }
                else
                {
                    DataRow ParentRow = SourceRow.GetParentRow(Field.RelationName);
                    DestRow[Field.FieldName] = ParentRow[Field.FieldName];
                }
            }
            DestTable.Rows.Add(DestRow);
        }
    }
}
				

SelectJoinInto Method

This section contains the code for theSelectJoinInto?????? ??? This method is a combination of theCreateJoinTable??InsertJoinInto???????? TheSelectJoinIntomethod creates a newDataTablebased on existingDataTableobjects and copies records that are sorted and filtered into the newDataTable.

????? ?? ??? ?????? ????? ??SelectJoinInto????:
dt = dsHelper.SelectInto("TestTable", ds.Tables["Employees"], 
    "FirstName FName,LastName LName,DepartmentEmployee.DepartmentName Department", "EmployeeID<5", "BirthDate");
				
This sample call creates aDataTable??? ????????? ?? ??? TestTable ?? ??? ??? ?? ??? ????? FirstName ?? ??????????? ?? LastName ????? ?? ?????? ???DataTable?? ?? DepartmentName ??????DataTable?? DepartmentEmployee ?????? ???????? ??DataRelation. ???? ??? ?? ????? ???????? ?????? ??????????? ??DataTableTestTable ???? ?? ???DataTable, ??? ?? "EmployeeID ?????? ??? ?? ??<5" and="" is="" sorted="" by=""></5">

???:: ?????? ?? ????? ????????????? ????? ?????? ?? ??? ???? ?? ??????? ???????? ?? ???? ???? ?????

??? ???? ?? ???SelectJoinInto???? ??????, ?? ??? ????? ???? ??????DataSetHelper???? ??? ???? ?? ""??????:
public DataTable SelectJoinInto(string TableName, DataTable SourceTable, string FieldList, string RowFilter, string Sort)
{
    /*
     * Selects sorted, filtered values from one DataTable to another.
     * Allows you to specify relationname.fieldname in the FieldList to include fields from
     *  a parent table. The Sort and Filter only apply to the base table and not to related tables.
    */ 
    DataTable dt = CreateJoinTable(TableName, SourceTable, FieldList);
    InsertJoinInto(dt, SourceTable, FieldList, RowFilter, Sort);
    return dt;
}
				

????????? ?? ??????? ????

  1. ?????? ?? ?? ?????? ????DataSetHelper???? ???? ????? ?????? ??? ????? ???
  2. ??? ??? ????? C# Windows ????????? ????? ?? ???, ????? ????? ?? ???? ????:
    1. Visual Studio .NET ?? ??????? ?????
    2. ????? ???????????? ??,????? ????-????? ????, ?? ???? ????????????.
    3. ???????? ?????????????? ????? ???, ????? ????????? C# ??????????? ???????????????? ???????? ????-????? ????, ?? ???? ???Windows ??????????? ???????????????.
  3. ?????? Explorer ???, ?????? ?? ????-????? ????, ?? ???? ??? ????? ?????????? ????????? ??????. DataSetHelper ????????? ???????
  4. ????? ????????????????? ??,?????? ??????.
  5. ??????????? ??????????? ????? ???, ????? ????????????????, ?? ???? ??? Windows ??????? ????????? ?? ??? DataSetHelper ????????? ?? ??? ??? ?????? ???????
  6. ??????? designer ??? ?????? ?????????????? ?? ??DataGrid??????? ?? ??? ???????? ????? ????? ??? ?? ????? ??? ???btnCreateJoin,btnInsertJoinInto, ??btnSelectJoinInto. ?? ??? ??????? ??? ????DataGrid???????? (dataGrid1)?
  7. ??????? ??? ??? ??? ???????? ????? ??????? ????? ?? ???? ??? ?? ??? ?????:
    using System.Data;
    					
  8. ??????? ???????? ???? ?? ??? ????? ?? declarations ??????:
    DataSet ds; DataSetHelper.DataSetHelper dsHelper;
    					
  9. ????? ??? ??????Form_Load?????:
    ds = new DataSet();
    dsHelper = new DataSetHelper.DataSetHelper(ref ds);
    //Create source tables
    DataTable dt = new DataTable("Employees");
    dt.Columns.Add("EmployeeID",Type.GetType("System.Int32") );
    dt.Columns.Add("FirstName", Type.GetType("System.String"));
    dt.Columns.Add("LastName", Type.GetType("System.String"));
    dt.Columns.Add("BirthDate", Type.GetType("System.DateTime"));
    dt.Columns.Add("JobTitle", Type.GetType("System.String"));
    dt.Columns.Add("DepartmentID", Type.GetType("System.Int32"));
    dt.Rows.Add(new object[] {1, "Tommy", "Hill", new DateTime(1970, 12, 31),  "Manager", 42});
    dt.Rows.Add(new object[] {2, "Brooke", "Sheals", new DateTime(1977, 12, 31), "Manager", 23});
    dt.Rows.Add(new object[] {3, "Bill", "Blast", new DateTime(1982, 5, 6), "Sales Clerk", 42});
    dt.Rows.Add(new object[] {1, "Kevin", "Kline", new DateTime(1978, 5, 13), "Sales Clerk", 42});
    dt.Rows.Add(new object[] {1, "Martha", "Seward", new DateTime(1976, 7, 4), "Sales Clerk", 23});
    dt.Rows.Add(new object[] {1, "Dora", "Smith", new DateTime(1985, 10, 22), "Trainee", 42});
    dt.Rows.Add(new object[] {1, "Elvis", "Pressman", new DateTime(1972, 11, 5), "Manager", 15});
    dt.Rows.Add(new object[] {1, "Johnny", "Cache", new DateTime(1984, 1, 23), "Sales Clerk", 15});
    dt.Rows.Add(new object[] {1, "Jean", "Hill", new DateTime(1979, 4, 14), "Sales Clerk", 42});
    dt.Rows.Add(new object[] {1, "Anna", "Smith", new DateTime(1985, 6, 26), "Trainee", 15});
    ds.Tables.Add(dt);
    
    dt = new DataTable("Departments");
    dt.Columns.Add("DepartmentID", Type.GetType("System.Int32"));
    dt.Columns.Add("DepartmentName", Type.GetType("System.String"));
    dt.Rows.Add(new object[] {15, "Men's Clothing"});
    dt.Rows.Add(new object[] {23, "Women's Clothing"});
    dt.Rows.Add(new object[] {42, "Children's Clothing"});
    ds.Tables.Add(dt);
    
    ds.Relations.Add("DepartmentEmployee",     ds.Tables["Departments"].Columns["DepartmentID"], 
        ds.Tables["Employees"].Columns["DepartmentID"]);
    					
  10. ????? ??? ??????btnCreateJoin_Click?????:
    dsHelper.CreateJoinTable("EmpDept",ds.Tables["Employees"], 
        "FirstName FName,LastName LName,BirthDate,DepartmentEmployee.DepartmentName Department");
    dataGrid1.SetDataBinding(ds, "EmpDept");
    					
  11. ????? ??? ??????btnInsertJoinInto_Click?????:
    dsHelper.InsertJoinInto(ds.Tables["EmpDept"], ds.Tables["Employees"], 
        "FirstName FName,LastName LName,BirthDate,DepartmentEmployee.DepartmentName Department",
        "JobTitle='Sales Clerk'", "DepartmentID");
    dataGrid1.SetDataBinding(ds, "EmpDept");
    					
  12. ????? ??? ??????btnSelectJoinInto_Click?????:
    dsHelper.SelectJoinInto("EmpDept2", ds.Tables["Employees"],
        "FirstName,LastName,BirthDate BDate,DepartmentEmployee.DepartmentName Department", 
        "JobTitle='Manager'", "DepartmentID");
    dataGrid1.SetDataBinding(ds, "EmpDept2");
    					
  13. Run the application, and then click each of the buttons. ?? ?????DataGridis populated with the tables and the data from the code.

    ???:: You can only click thebtnCreateJoin??btnSelectJoinIntobuttons one time. If you click either of these buttons more than one time, you receive an error message that you are trying to add the same table two times. Additionally, you must clickbtnCreateJoinbefore you clickbtnInsertJoinInto; otherwise, the destinationDataTableis not created. ??? ?? ????? ????? ?? ???? ??? ????btnInsertJoinIntobutton multiple times, you populate theDataGridwith duplicate records.

??????????? ????

  • TheColumnName??DataTypeproperties are the only properties that are copied to the destinationDataTable. You can extend theCreateTablemethod to copy additional properties, such as theMaxLengthproperty, or you can create new key columns.
  • The??????????property is not copied; instead, the evaluated result is copied. Therefore, you do not have to add fields that are referenced by the expression to the destination table. Additionally, the destination column can appear earlier in the result list than any of the columns that this column depends on otherwise. You can modify theCreateTablemethod to copy the??????????(the InsertInto column ignores columns with an??????????), ?????? ?? ???? ?? ?????? ???? ?? ???????? ??? ????? ??? ???
  • ?? ??????????? ?? ???? ?? ???? ???CreateJoinTable,InsertJoinInto, ??SelectJoinInto??? ???????CreateTable,InsertInto, ??SelectInto???????? ?? ???? ??? ???????? ??????? ?? ???CreateTable,InsertInto, ??SelectInto??????? ?? ???, ????? ???? ?????? ????? ???? ?? Microsoft ???????? ??? ?????:
    326009HOWTO: ??????????? ?? DataSet SELECT ??? ????? ???? ??? ????? C# .NET
    ??? ?? ?? ??????? ?? ???? ???? ?? ??? ???? ????? ???, ????? ??? ???? ??? ???? ??? ???? ??? ??????? ?? ????? ??? ??, ?? ?? ????? ?? ???? ???CreateJoinTable??InsertJoinInto?????? ????? ?? ???? ???? ????? ???? ?? ????? ???? ?? ??? ???????Throw??? ?? ??? ???? ?? ??? uncommenting ??????CreateTable??InsertInto??????? ??? ?? ????? ?????????:
        if (FieldList==null)
        {
            throw new ArgumentException("You must specify at least one field in the field list.");
            //return CreateTable(TableName, SourceTable);
        }
    					
    -??-
        if (FieldList==null)
        {
            throw new ArgumentException("You must specify at least one field in the field list.");
            //InsertInto(DestTable, SourceTable, RowFilter, Sort);
        }
    					

?????? ??????

  • ?? fieldname ?? ????? ???? ?? ???? ??? ?? ??? ?????? ???? ???? ????DataColumn?????? conventions. ?????????? ?????? ?? ???? ??? ??, ?? ??? ??? ?????? (.), ?? ???? ???? ????? (,) ?? ?????????, ?? ???? ????? ()?
  • ??? ?? ???? ??? ?? ?? ???? ??? ????? ????, ?? ?? ?????? ?? ?? ??? ??? ?????DataSet, ?????? ??? ????? ??? ??????? ?? ?????? ?? ?? ???? ?? ??? ?? ??? ?? ??? ???? ?? ??? ??????? ????????? ??? ???? ???? ?? ??DataTable???? ??? ??? ?? ?? ????? ??? ???????? ??? ??, ?? ??? ???? ???DataSetHelper???? ?? ???? ?? ??? ??? ?????? ?? ???? ????DataSet?? ??? ?????DataGrid.DataSource???? ?? ??? ???? ???dt?? ?? ???? ?? ????? ??SetDataBinding???? ????
  • ??? ????? ?????? ????? ???? ?????? (??????, ?? ????) ?? ????? ???? ??, ?? ?? ??? ?? ???? ?? ??? ?????? ????InsertJoinInto?? ??? ???? ?? ????????? ???? ?? ??? ?????? ??? ??????, ???? ?? ?????? ???? ???

???

???? ID: 326080 - ????? ???????: 04 ?????? 2010 - ??????: 2.0
???? ???? ???? ??:
  • Microsoft ADO.NET 1.1
  • Microsoft Visual C# .NET 2003 Standard Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
??????: 
kbhowtomaster kbsystemdata kbmt KB326080 KbMthi
???? ?????? ????????
??????????: ?? ???? ?? ???? ??????? ?? ????? ?? Microsoft ????-?????? ?????????? ?????? ?????? ???? ??? ??. Microsoft ???? ??? ????-???????? ?? ????-???????? ????? ?????? ?? ???? ???????? ???? ?? ???? ????? ????? ??? ?? ??? ?????? ?? ???? ???? ???? ??? ????? ??. ???????, ????-???????? ???? ????? ???? ???? ???? ???. ?????, ????????, ?????-???? ?? ??????? ?? ???????? ?? ???? ???, ???? ?? ??? ?????? ???? ???? ??? ????? ??? ?? ???? ??. Microsoft ??????? ??? ???? ?? ?????? ?? ??????????, ????????? ?? ??? ?????? ?? ???? ????? ?? ???? ???????? ?? ??? ???? ????? ?? ??? ????????? ???? ??. Microsoft ????-?????? ?????????? ?? ????? ?????? ?? ?? ??? ??.
?????????? ?? ??????? ????????? ??????? ??:326080

??????????? ???

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com