In C#, the data read from the database is generally stored in the datatable. datatable is actually a table, just like copying the retrieved results from the database into the datatable. The internal data structure of datatable is like this two-dimensional table.
Here are several usages in datatable.
Add a reference
//Reference namespaceusing ;
Create a table
//Create an empty tableDataTable dt = new DataTable(); //Create an empty table named "new-tabel";DataTable dt = new DataTable("new-tabel");
Create a column
//1. Create an empty columnDataColumn dc = new DataColumn(); //Add empty column to dt table(dc); //2. Create a column with column name and type name (optional one of the two methods)("column0", ("")); ("column0", typeof(String)); //3. Add columns through column schemaDataColumn dc = new DataColumn("column1",("")); DataColumn dc = new DataColumn("column1", typeof(DateTime)); (dc);
Create a row
//1. Create empty linesDataRow dr = (); (dr); //2. Create empty lines(); //3. Create and assign values through line frame("Zhang San",);//The data order of the parameters in Add should correspond to the order of the columns in dt//4. Create by copying a row of the dt2 table([i].ItemArray);
Value and assignment
//Assignment of new rowDataRow dr = (); dr[0] = "Zhang San";// Assign values through indexdr["column1"] = ; // Assign value by name// Assign a value to the existing rows in the table[0][0] = "Zhang San"; // Assign values through index[0]["column1"] = ;// Assign value by name//Get the valuestring name=[0][0].ToString(); string time=[0]["column1"].ToString(); fromdatatableWhen taking the value in therowsproperty。 If you traverse the value of a certain line。 foreach(DataColumn col in ) (row[col]); //row is an instance of datarow, referring to a specific row. You can also write this way and it may be easy to understand foreach(DataColumn col in ) (.[0][col]); aboutdatarow
Filter rows
//Select a collection of rows with column1 column value emptyDataRow[] drs = ("column1 is null"); //Select the set of rows with column value of "Li Si"DataRow[] drs = ("column0 = 'Li Si'"); //Filter a collection of rows with "table" in column0 column value (fuzzy query)DataRow[] drs = ("column0 like 'Zhang %'");//If you have multiple conditions filtering, you can add and or or//Filter the set of rows with "table" in column0 column value and sort it in descending order of column1DataRow[] drs = ("column0 like 'Zhang %'", "column1 DESC"); //() get all rowsDatarow[] drs=(); //At this time drs is all rows in the dt data table.//(sting) Get rows that match the filter criteria, in primary key order (if there is no primary key, in order to add)Datarow[] drs=("A='bbc'"); //At this time drs is the number of rows with the value of ""bbc" in the dt data table.
Delete rows
//Use the (DataRow) method([0]); //Use (index) method(0); //Use the() method[0].Delete(); (); //-----Differences and points of attention-----//Remove() and RemoveAt() methods are directly deleted//The Delete() method just marks the line as deleted, but it still exists. It can also roll back () to make the line undelete.// When used to get the number of rows, it is still necessary to delete the previous number of rows. You need to use the () method to submit the modification.//If you want to delete multiple rows in DataTable, you should use reverse order loops, and you cannot use foreach to loop delete, because the index will change during positive order deletion, and the program will have an exception, which is difficult to predict the consequences.for (int i = - 1; i >= 0; i--) { (i); }
Copy line
//Copy the table, and copy the table structure and data in the table at the same timeDataTable dtNew = new DataTable(); dtNew = (); //Copy the tableDataTable dtNew = (); //Copy the data structure of the dt table() //Clear datafor (int i = 0; i < ; i++) { if (Conditional statements) { ([i].ItemArray); //Add data rows } } //Clone the table, just copy the table structure, not including dataDataTable dtNew = new DataTable(); dtNew = (); //If only a row in a table is neededDataTable dtNew = new DataTable(); dtNew = (); ();//Clear table data([0]);//This is the first line
Table sorting
DataTable dt = new DataTable();//Create a table("ID", typeof(Int32));//Add column("Name", typeof(String)); ("Age", typeof(Int32)); (new object[] { 1, "Zhang San" ,20});//Add row(new object[] { 2, "Li Si" ,25}); (new object[] { 3, "Wang Wu" ,30}); DataView dv = ;//Get table view = "ID DESC";//Sort in reverse order by ID();//Convert to table
The following excerpts of two codes can help you understand the two classes of datarow and datacolumn for a deeper understanding.
If you have read all the above, please be sure to read all the following
private void CreateNewDataRow() { // Use the MakeTable function below to create a new table. DataTable table; table = MakeNamesTable(); // Once a table has been created, use the // NewRow to create a DataRow. DataRow row; row = (); // Then add the new row to the collection. row["fName"] = "John"; row["lName"] = "Smith"; (row); foreach(DataColumn column in ) (); =table; } private DataTable MakeNamesTable() { // Create a new DataTable titled 'Names.' DataTable namesTable = new DataTable("Names"); // Add three column objects to the table. DataColumn idColumn = new DataColumn(); = ("System.Int32"); = "id"; = true; (idColumn); DataColumn fNameColumn = new DataColumn(); = (""); = "Fname"; = "Fname"; (fNameColumn); DataColumn lNameColumn = new DataColumn(); = (""); = "LName"; (lNameColumn); // Create an array for DataColumn objects. DataColumn [] keys = new DataColumn [1]; keys[0] = idColumn; = keys; // Return the new DataTable. return namesTable; }
private void DemonstrateAcceptChanges() { //Run a function to create a DataTable with one column. DataTable table = MakeTable(); DataRow row; // Create a new DataRow. row = (); // Detached row. ("New Row " + ); (row); // New row. ("AddRow " + ); (); // Unchanged row. ("AcceptChanges " + ); row["FirstName"] = "Scott"; // Modified row. ("Modified " + ); (); // Deleted row. ("Deleted " + ); } private DataTable MakeTable() { // Make a simple table with one column. DataTable table = new DataTable("table"); DataColumn fnameColumn = new DataColumn( "FirstName", ("")); (fnameColumn); return table; }
The following is a dataset that is closely related to datatable
DataSet is a memory-resident representation of data that provides a consistent relational programming model regardless of the data source it contains. DataSet represents the entire dataset, which contains tables that include, sort, and constrain data, and relationships between tables.
There are several methods that use DataSet, which can be applied individually or in combination. you can:
Create DataRelation, Constraint, and DataSet programmatically in DataTable and populate the table with data.
Populate DataAdapter with data tables from existing relational data sources via DataSet.
Datatable can only be assigned to one dataset. If you want to assign to multiple datasets, please copy multiple datatables;
Dataset is a dataset that can store multiple datatables.
Data in dataset can also be converted into datatable.
Supplement: Common processing of C# dataTable
Look at the code ~
var l2 = ().ToList().Select(x => (“ID”)).ToList(); DataTable new dt = new DataTable(); newdt = (); //Clone the structure of dt, including all dt architectures and constraints, and has no data;DataRow[] rows = (conditions); // Query records that meet the criteria from dt;(“City Like ‘B%'”); (“name='” + a +"'"); foreach (DataRow row in rows) // Add the result of the query to dt;{ (); }
The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.