在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
一、DataTable简介 (2) 常用属性
DataTable dt = new DataTable("Table_AX");
(2)Add columns for DataTable //方法一: dt.Columns.Add("column0", System.Type.GetType("System.String")); //方法二: 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 如果没有赋值,则用is null来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 //对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);
(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 //绑定的其实是DefaultView gvTestDataTable.DataSource = dt; gvTestDataTable.DataBind();
(13)judge the DataTable's Column name is a string //判断一个字符串是否为DataTable的列名 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; }
|
请发表评论