C # common usage of DataTable,

Source: Internet
Author: User

C # common usage of DataTable,

DataTable is often used in projects. If DataTable is used properly, it not only makes the program concise and practical, but also improves performance and achieves twice the result with half the effort. The usage skills of DataTable are summarized.

1. DataTable Introduction

(1) constructor
DataTable () initializes a new instance of the DataTable class without parameters.
DataTable (string tableName) uses the specified table name to initialize a new instance of the DataTable class.
DataTable (string tableName, string tableNamespace) uses the specified table name and namespace to initialize a new instance of the DataTable class.
(2) common attributes
CaseSensitive indicates whether the string comparison in the table is case sensitive.
ChildRelations obtains the set of child relations of this able.
Columns obtains the set of Columns that belong to the table.
Constraints obtains the set of Constraints maintained by the table.
DataSet obtains the DataSet to which the table belongs.
DefaultView: obtains the custom view of a table that may contain a filtering view or a cursor position.
HasErrors gets a value that indicates whether there is an error in any row of any table in the DataSet to which the table belongs.
MinimumCapacity gets or sets the initial start size of the table. The initial starting size of the row in the table. The default value is 50.
Rows obtains the set of Rows belonging to the table.
TableName: Get or set the name of the DataTable.

(3) Common Methods
AcceptChanges () submits all changes made to the table since the last call of AcceptChanges.
BeginInit () starts to initialize the able that is used on the form or used by another component. Initialization occurs at runtime.

Clear () clears the DataTable of all data.
Clone (): Clone the structure of the able, including all the DataTable architectures and constraints.
EndInit () ends the initialization of the able used on the form or used by another component. Initialization occurs at runtime.
ImportRow (DataRow row) Copies DataRow to the DataTable, retaining any attribute settings, initial values, and current values.
Merge (DataTable table) combines the specified able with the current DataTable.
NewRow () creates a new DataRow with the same schema as the table.
2. DataTable usage skills

(1) Create a DataTable

DataTable dt = new DataTable("Table_AX");

(2) Add columns for DataTable

//Method 1        dt.Columns.Add("column0", System.Type.GetType("System.String"));        //Method 2        DataColumn dc = new DataColumn("column1", System.Type.GetType("System.Boolean"));        dt.Columns.Add(dc); 

(3) Add rows for DataTable

//Initialize the row         DataRow dr = dt.NewRow();         dr["column0"] = "AX";         dr["column1"] = true;         dt.Rows.Add(dr);         //Doesn't initialize the row         DataRow dr1 = dt.NewRow();         dt.Rows.Add(dr1);
 

(4) Select row

// Search the second row if no value is assigned, use is null to select DataRow [] drs = dt. select ("column1 is null"); DataRow [] drss = dt. select ("column0 = 'ax '");

(5) Copy DataTable include data

DataTable dtNew = dt.Copy();


(6) Copy DataTable only scheme

DataTable dtOnlyScheme = dt.Clone();

 
(7) Operate one row

 
// Operation on dt // Method 1 DataRow drOperate = dt. rows [0]; drOperate ["column0"] = "AXzhz"; drOperate ["column1"] = false; // Method 2 drOperate [0] = "AXzhz "; drOperate [1] = false; // Method 3 dt. rows [0] ["column0"] = "AXzhz"; dt. rows [0] ["column1"] = false; // Method 4 dt. rows [0] [0] = "AXzhz"; dt. rows [0] [1] = false;
 


(8) Evaluate another DataTable's row to current Datatable

dtOnlyScheme.Rows.Add(dt.Rows[0].ItemArray);


(9) Convert to string

System.IO.StringWriter sw = new System.IO.StringWriter();         System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(sw);         dt.WriteXml(xw);         string s = sw.ToString();


(10) Filter DataTable

dt.DefaultView.RowFilter = "column1 <> true";         dt.DefaultView.RowFilter = "column1 = true";


(11) Sort row

dt.DefaultView.Sort = "ID ,Name ASC";          dt=dt.DefaultView.ToTable();


(12) Bind DataTable

// The binding is actually defaview view gvtestable able. DataSource = dt; gvTestDataTable. DataBind ();


(13) judge the DataTable's Column name is a string

// Determine whether a string is the DataTable column name dtInfo. Columns. Contains ("AX ");


(14) DataTable convert to XML and XML convert to DataTable

 
protected void Page_Load(object sender, EventArgs e)          {             DataTable dt_AX = new DataTable();             //dt_AX.Columns.Add("Sex", typeof(System.Boolean));             //DataRow dr = dt_AX.NewRow();             //dr["Sex"] = true;             //dt_AX.Rows.Add(dr);             string xml=ConvertBetweenDataTableAndXML_AX(dt_AX);             DataTable dt = ConvertBetweenDataTableAndXML_AX(xml);         }         public string ConvertBetweenDataTableAndXML_AX(DataTable dtNeedCoveret)        {             System.IO.TextWriter tw = new System.IO.StringWriter();             //if TableName is empty, WriteXml() will throw Exception.                 dtNeedCoveret.TableName=dtNeedCoveret.TableName.Length==0?"Table_AX":dtNeedCoveret.TableName;             dtNeedCoveret.WriteXml(tw);             dtNeedCoveret.WriteXmlSchema(tw);             return tw.ToString();        }         public DataTable ConvertBetweenDataTableAndXML_AX(string xml)        {             System.IO.TextReader trDataTable = new System.IO.StringReader(xml.Substring(0, xml.IndexOf("<?xml")));             System.IO.TextReader trSchema = new System.IO.StringReader(xml.Substring(xml.IndexOf("<?xml")));             DataTable dtReturn = new DataTable();             dtReturn.ReadXmlSchema(trSchema);             dtReturn.ReadXml(trDataTable);             return dtReturn;        }

(15) execute a query in the DataTable and return the DataTable;

Method 1:

// <Summary> // execute the query in the DataTable to return the new DataTable // </summary> // dt is the source data DataTable // condition is the query condition DataTable newdt = new DataTable (); newdt = dt. clone (); // Clone the dt structure, including all dt architectures and constraints without data; DataRow [] rows = dt. select (conditions); // query qualified records from dt; foreach (DataRow row in rows) // Add the query results to dt; {newdt. rows. add (row. itemArray );}

 

Method 2:

DataTable newdt = new DataTable();newdt=dt.Clone();DataRow[] dr = dt.Select(condition);for(int i=0;i<dr.Length;i++){newdt.ImportRow((DataRow)dr[i]);}

 

Method 3:

DataTable newdt = new DataTable();dt.DefaultView.RowFilter = "conditions";newdt =dt.DefaultView.ToTable();

(16) delete rows in the DataTable:

Three methods for deleting Rows in a able are as follows: (DataTable. Rows. Remove (DataRow dr), DataTable. Rows. RemoveAt (I), and DataRow. Delete ())

To delete rows in a able, pay attention to indexing. There are two methods:
1] when using a for loop, note that the initial value of the counter is the table length and the auto-reduction cycle. DataTable. Rows. RemoveAt (I.
2) use the Select method of DataTable. Note that the parameter of this method is a string filter.
3] datatable is required after Delete. the AccepteChanges () method confirms that the data is completely deleted. Because Delete () only marks the status of the corresponding column as deleted, you can also use datatable. the RejectChanges () rollback cancels the deletion of this row. To Delete multiple rows, you can use Delete () consecutively and then use the AccepteChanges () method to confirm the deletion.


Symbol in C Language <Yes

Left shift operator (<)

Removes all the binary bits of an operation object from the left and adds 0 to the right ).

For example, a = a <2 shifts the binary bits of a two places to the left and complements 0 to the right,

Move 1 to the left and then a = a * 2;

If the left shift does not include 1 in the Discard high position, then shifts one bit left, which is equivalent to multiplying the number by 2.
Shift right operator (>)

Shifts all the binary bits of a number to several places to the right, and adds 0 to the left of the positive number, 1 to the left of the negative number, and discards the right of the negative number.

The operand shifts one digit to the right, which is equivalent to dividing the number by 2.

For example, a = a> 2 shifts the binary bit of a two places to the right,

0 or 1 to see whether the number is positive or negative.

Symbol in C Language <Yes

Left shift operator (<)

Removes all the binary bits of an operation object from the left and adds 0 to the right ).

For example, a = a <2 shifts the binary bits of a two places to the left and complements 0 to the right,

Move 1 to the left and then a = a * 2;

If the left shift does not include 1 in the Discard high position, then shifts one bit left, which is equivalent to multiplying the number by 2.
Shift right operator (>)

Shifts all the binary bits of a number to several places to the right, and adds 0 to the left of the positive number, 1 to the left of the negative number, and discards the right of the negative number.

The operand shifts one digit to the right, which is equivalent to dividing the number by 2.

For example, a = a> 2 shifts the binary bit of a two places to the right,

0 or 1 to see whether the number is positive or negative.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.