DataTable.cs 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097
  1. //
  2. // System.Data.DataTable.cs
  3. //
  4. // Author:
  5. // Franklin Wise <[email protected]>
  6. // Christopher Podurgiel ([email protected])
  7. // Daniel Morgan <[email protected]>
  8. // Rodrigo Moya <[email protected]>
  9. // Tim Coleman ([email protected])
  10. // Ville Palo <[email protected]>
  11. // Sureshkumar T <[email protected]>
  12. // Konstantin Triger <[email protected]>
  13. //
  14. // (C) Chris Podurgiel
  15. // (C) Ximian, Inc 2002
  16. // Copyright (C) Tim Coleman, 2002-2003
  17. // Copyright (C) Daniel Morgan, 2002-2003
  18. //
  19. //
  20. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  21. //
  22. // Permission is hereby granted, free of charge, to any person obtaining
  23. // a copy of this software and associated documentation files (the
  24. // "Software"), to deal in the Software without restriction, including
  25. // without limitation the rights to use, copy, modify, merge, publish,
  26. // distribute, sublicense, and/or sell copies of the Software, and to
  27. // permit persons to whom the Software is furnished to do so, subject to
  28. // the following conditions:
  29. //
  30. // The above copyright notice and this permission notice shall be
  31. // included in all copies or substantial portions of the Software.
  32. //
  33. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  34. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  35. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  36. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  37. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  38. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  39. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  40. //
  41. using System;
  42. using System.Data.Common;
  43. using System.Collections;
  44. using System.ComponentModel;
  45. using System.Globalization;
  46. using System.IO;
  47. using System.Runtime.Serialization;
  48. using System.Xml;
  49. using System.Xml.Schema;
  50. using System.Text.RegularExpressions;
  51. using Mono.Data.SqlExpressions;
  52. namespace System.Data {
  53. //[Designer]
  54. [ToolboxItem (false)]
  55. [DefaultEvent ("RowChanging")]
  56. [DefaultProperty ("TableName")]
  57. [DesignTimeVisible (false)]
  58. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DataTableEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  59. [Serializable]
  60. public class DataTable : MarshalByValueComponent, IListSource, ISupportInitialize, ISerializable
  61. {
  62. #region Fields
  63. internal DataSet dataSet;
  64. private bool _caseSensitive;
  65. private DataColumnCollection _columnCollection;
  66. private ConstraintCollection _constraintCollection;
  67. // never access it. Use DefaultView.
  68. private DataView _defaultView = null;
  69. private string _displayExpression;
  70. private PropertyCollection _extendedProperties;
  71. private bool _hasErrors;
  72. private CultureInfo _locale;
  73. private int _minimumCapacity;
  74. private string _nameSpace;
  75. private DataRelationCollection _childRelations;
  76. private DataRelationCollection _parentRelations;
  77. private string _prefix;
  78. private UniqueConstraint _primaryKeyConstraint;
  79. private DataRowCollection _rows;
  80. private ISite _site;
  81. private string _tableName;
  82. private bool _containsListCollection;
  83. private string _encodedTableName;
  84. internal bool _duringDataLoad;
  85. internal bool _nullConstraintViolationDuringDataLoad;
  86. private bool dataSetPrevEnforceConstraints;
  87. private bool dataTablePrevEnforceConstraints;
  88. private bool enforceConstraints = true;
  89. private DataRowBuilder _rowBuilder;
  90. private ArrayList _indexes;
  91. private RecordCache _recordCache;
  92. private int _defaultValuesRowIndex = -1;
  93. protected internal bool fInitInProgress;
  94. // If CaseSensitive property is changed once it does not anymore follow owner DataSet's
  95. // CaseSensitive property. So when you lost you virginity it's gone for ever
  96. private bool _virginCaseSensitive = true;
  97. private PropertyDescriptorCollection _propertyDescriptorsCache;
  98. static DataColumn[] _emptyColumnArray = new DataColumn[0];
  99. // Regex to parse the Sort string.
  100. static Regex SortRegex = new Regex ( @"^((\[(?<ColName>.+)\])|(?<ColName>\S+))([ ]+(?<Order>ASC|DESC))?$",
  101. RegexOptions.IgnoreCase|RegexOptions.ExplicitCapture);
  102. DataColumn[] _latestPrimaryKeyCols;
  103. #endregion //Fields
  104. /// <summary>
  105. /// Initializes a new instance of the DataTable class with no arguments.
  106. /// </summary>
  107. public DataTable ()
  108. {
  109. dataSet = null;
  110. _columnCollection = new DataColumnCollection(this);
  111. _constraintCollection = new ConstraintCollection(this);
  112. _extendedProperties = new PropertyCollection();
  113. _tableName = "";
  114. _nameSpace = null;
  115. _caseSensitive = false; //default value
  116. _displayExpression = null;
  117. _primaryKeyConstraint = null;
  118. _site = null;
  119. _rows = new DataRowCollection (this);
  120. _indexes = new ArrayList();
  121. _recordCache = new RecordCache(this);
  122. //LAMESPEC: spec says 25 impl does 50
  123. _minimumCapacity = 50;
  124. _childRelations = new DataRelationCollection.DataTableRelationCollection (this);
  125. _parentRelations = new DataRelationCollection.DataTableRelationCollection (this);
  126. }
  127. /// <summary>
  128. /// Intitalizes a new instance of the DataTable class with the specified table name.
  129. /// </summary>
  130. public DataTable (string tableName) : this ()
  131. {
  132. _tableName = tableName;
  133. }
  134. /// <summary>
  135. /// Initializes a new instance of the DataTable class with the SerializationInfo and the StreamingContext.
  136. /// </summary>
  137. [MonoTODO]
  138. protected DataTable (SerializationInfo info, StreamingContext context)
  139. : this ()
  140. {
  141. string schema = info.GetString ("XmlSchema");
  142. string data = info.GetString ("XmlDiffGram");
  143. DataSet ds = new DataSet ();
  144. ds.ReadXmlSchema (new StringReader (schema));
  145. ds.Tables [0].CopyProperties (this);
  146. ds = new DataSet ();
  147. ds.Tables.Add (this);
  148. ds.ReadXml (new StringReader (data), XmlReadMode.DiffGram);
  149. ds.Tables.Remove (this);
  150. /* keeping for a while. With the change above, we shouldn't have to consider
  151. * DataTable mode in schema inference/read.
  152. XmlSchemaMapper mapper = new XmlSchemaMapper (this);
  153. XmlTextReader xtr = new XmlTextReader(new StringReader (schema));
  154. mapper.Read (xtr);
  155. XmlDiffLoader loader = new XmlDiffLoader (this);
  156. xtr = new XmlTextReader(new StringReader (data));
  157. loader.Load (xtr);
  158. */
  159. }
  160. #if NET_2_0
  161. public DataTable (string tableName, string tbNamespace)
  162. : this (tableName)
  163. {
  164. _nameSpace = tbNamespace;
  165. }
  166. #endif
  167. /// <summary>
  168. /// Indicates whether string comparisons within the table are case-sensitive.
  169. /// </summary>
  170. #if !NET_2_0
  171. [DataSysDescription ("Indicates whether comparing strings within the table is case sensitive.")]
  172. #endif
  173. public bool CaseSensitive {
  174. get {
  175. if (_virginCaseSensitive && dataSet != null)
  176. return dataSet.CaseSensitive;
  177. else
  178. return _caseSensitive;
  179. }
  180. set {
  181. if (_childRelations.Count > 0 || _parentRelations.Count > 0) {
  182. throw new ArgumentException ("Cannot change CaseSensitive or Locale property. This change would lead to at least one DataRelation or Constraint to have different Locale or CaseSensitive settings between its related tables.");
  183. }
  184. _virginCaseSensitive = false;
  185. _caseSensitive = value;
  186. ResetCaseSensitiveIndexes();
  187. }
  188. }
  189. internal ArrayList Indexes{
  190. get { return _indexes; }
  191. }
  192. internal void ChangedDataColumn (DataRow dr, DataColumn dc, object pv)
  193. {
  194. DataColumnChangeEventArgs e = new DataColumnChangeEventArgs (dr, dc, pv);
  195. OnColumnChanged(e);
  196. }
  197. internal void ChangingDataColumn (DataRow dr, DataColumn dc, object pv)
  198. {
  199. DataColumnChangeEventArgs e = new DataColumnChangeEventArgs (dr, dc, pv);
  200. OnColumnChanging (e);
  201. }
  202. internal void DeletedDataRow (DataRow dr, DataRowAction action)
  203. {
  204. DataRowChangeEventArgs e = new DataRowChangeEventArgs (dr, action);
  205. OnRowDeleted (e);
  206. }
  207. internal void DeletingDataRow (DataRow dr, DataRowAction action)
  208. {
  209. DataRowChangeEventArgs e = new DataRowChangeEventArgs (dr, action);
  210. OnRowDeleting(e);
  211. }
  212. internal void ChangedDataRow (DataRow dr, DataRowAction action)
  213. {
  214. DataRowChangeEventArgs e = new DataRowChangeEventArgs (dr, action);
  215. OnRowChanged (e);
  216. }
  217. internal void ChangingDataRow (DataRow dr, DataRowAction action)
  218. {
  219. DataRowChangeEventArgs e = new DataRowChangeEventArgs (dr, action);
  220. OnRowChanging (e);
  221. }
  222. /// <summary>
  223. /// Gets the collection of child relations for this DataTable.
  224. /// </summary>
  225. [Browsable (false)]
  226. #if !NET_2_0
  227. [DataSysDescription ("Returns the child relations for this table.")]
  228. #endif
  229. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  230. public DataRelationCollection ChildRelations {
  231. get {
  232. return _childRelations;
  233. }
  234. }
  235. /// <summary>
  236. /// Gets the collection of columns that belong to this table.
  237. /// </summary>
  238. [DataCategory ("Data")]
  239. #if !NET_2_0
  240. [DataSysDescription ("The collection that holds the columns for this table.")]
  241. #endif
  242. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  243. public DataColumnCollection Columns {
  244. get { return _columnCollection; }
  245. }
  246. /// <summary>
  247. /// Gets the collection of constraints maintained by this table.
  248. /// </summary>
  249. [DataCategory ("Data")]
  250. #if !NET_2_0
  251. [DataSysDescription ("The collection that holds the constraints for this table.")]
  252. #endif
  253. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  254. public ConstraintCollection Constraints {
  255. get { return _constraintCollection; }
  256. }
  257. /// <summary>
  258. /// Gets the DataSet that this table belongs to.
  259. /// </summary>
  260. [Browsable (false)]
  261. #if !NET_2_0
  262. [DataSysDescription ("Indicates the DataSet to which this table belongs.")]
  263. #endif
  264. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  265. public DataSet DataSet {
  266. get { return dataSet; }
  267. }
  268. /// <summary>
  269. /// Gets a customized view of the table which may
  270. /// include a filtered view, or a cursor position.
  271. /// </summary>
  272. [MonoTODO]
  273. [Browsable (false)]
  274. #if !NET_2_0
  275. [DataSysDescription ("This is the default DataView for the table.")]
  276. #endif
  277. public DataView DefaultView {
  278. get {
  279. if (_defaultView == null) {
  280. lock(this){
  281. if (_defaultView == null){
  282. if (dataSet != null)
  283. _defaultView = dataSet.DefaultViewManager.CreateDataView(this);
  284. else
  285. _defaultView = new DataView(this);
  286. }
  287. }
  288. }
  289. return _defaultView;
  290. }
  291. }
  292. /// <summary>
  293. /// Gets or sets the expression that will return
  294. /// a value used to represent this table in the user interface.
  295. /// </summary>
  296. [DataCategory ("Data")]
  297. #if !NET_2_0
  298. [DataSysDescription ("The expression used to compute the data-bound value of this row.")]
  299. #endif
  300. [DefaultValue ("")]
  301. public string DisplayExpression {
  302. get { return _displayExpression == null ? "" : _displayExpression; }
  303. set { _displayExpression = value; }
  304. }
  305. /// <summary>
  306. /// Gets the collection of customized user information.
  307. /// </summary>
  308. [Browsable (false)]
  309. [DataCategory ("Data")]
  310. #if !NET_2_0
  311. [DataSysDescription ("The collection that holds custom user information.")]
  312. #endif
  313. public PropertyCollection ExtendedProperties {
  314. get { return _extendedProperties; }
  315. }
  316. /// <summary>
  317. /// Gets a value indicating whether there are errors in
  318. /// any of the_rows in any of the tables of the DataSet to
  319. /// which the table belongs.
  320. /// </summary>
  321. [Browsable (false)]
  322. #if !NET_2_0
  323. [DataSysDescription ("Returns whether the table has errors.")]
  324. #endif
  325. public bool HasErrors {
  326. get {
  327. // we can not use the _hasError flag because we do not know when to turn it off!
  328. for (int i = 0; i < _rows.Count; i++)
  329. {
  330. if (_rows[i].HasErrors)
  331. return true;
  332. }
  333. return false;
  334. }
  335. }
  336. /// <summary>
  337. /// Gets or sets the locale information used to
  338. /// compare strings within the table.
  339. /// </summary>
  340. #if !NET_2_0
  341. [DataSysDescription ("Indicates a locale under which to compare strings within the table.")]
  342. #endif
  343. public CultureInfo Locale {
  344. get {
  345. // if the locale is null, we check for the DataSet locale
  346. // and if the DataSet is null we return the current culture.
  347. // this way if DataSet locale is changed, only if there is no locale for
  348. // the DataTable it influece the Locale get;
  349. if (_locale != null)
  350. return _locale;
  351. if (DataSet != null)
  352. return DataSet.Locale;
  353. return CultureInfo.CurrentCulture;
  354. }
  355. set {
  356. if (_childRelations.Count > 0 || _parentRelations.Count > 0) {
  357. throw new ArgumentException ("Cannot change CaseSensitive or Locale property. This change would lead to at least one DataRelation or Constraint to have different Locale or CaseSensitive settings between its related tables.");
  358. }
  359. if (_locale == null || !_locale.Equals(value))
  360. _locale = value;
  361. }
  362. }
  363. /// <summary>
  364. /// Gets or sets the initial starting size for this table.
  365. /// </summary>
  366. [DataCategory ("Data")]
  367. #if !NET_2_0
  368. [DataSysDescription ("Indicates an initial starting size for this table.")]
  369. #endif
  370. [DefaultValue (50)]
  371. public int MinimumCapacity {
  372. get { return _minimumCapacity; }
  373. set { _minimumCapacity = value; }
  374. }
  375. /// <summary>
  376. /// Gets or sets the namespace for the XML represenation
  377. /// of the data stored in the DataTable.
  378. /// </summary>
  379. [DataCategory ("Data")]
  380. #if !NET_2_0
  381. [DataSysDescription ("Indicates the XML uri namespace for the elements contained in this table.")]
  382. #endif
  383. public string Namespace {
  384. get
  385. {
  386. if (_nameSpace != null)
  387. {
  388. return _nameSpace;
  389. }
  390. if (DataSet != null)
  391. {
  392. return DataSet.Namespace;
  393. }
  394. return String.Empty;
  395. }
  396. set { _nameSpace = value; }
  397. }
  398. /// <summary>
  399. /// Gets the collection of parent relations for
  400. /// this DataTable.
  401. /// </summary>
  402. [Browsable (false)]
  403. #if !NET_2_0
  404. [DataSysDescription ("Returns the parent relations for this table.")]
  405. #endif
  406. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  407. public DataRelationCollection ParentRelations {
  408. get {
  409. return _parentRelations;
  410. }
  411. }
  412. /// <summary>
  413. /// Gets or sets the namespace for the XML represenation
  414. /// of the data stored in the DataTable.
  415. /// </summary>
  416. [DataCategory ("Data")]
  417. #if !NET_2_0
  418. [DataSysDescription ("Indicates the Prefix of the namespace used for this table in XML representation.")]
  419. #endif
  420. [DefaultValue ("")]
  421. public string Prefix {
  422. get { return _prefix == null ? "" : _prefix; }
  423. set {
  424. // Prefix cannot contain any special characters other than '_' and ':'
  425. for (int i = 0; i < value.Length; i++) {
  426. if (!(Char.IsLetterOrDigit (value [i])) && (value [i] != '_') && (value [i] != ':'))
  427. throw new DataException ("Prefix '" + value + "' is not valid, because it contains special characters.");
  428. }
  429. _prefix = value;
  430. }
  431. }
  432. /// <summary>
  433. /// Gets or sets an array of columns that function as
  434. /// primary keys for the data table.
  435. /// </summary>
  436. [DataCategory ("Data")]
  437. #if !NET_2_0
  438. [DataSysDescription ("Indicates the column(s) that represent the primary key for this table.")]
  439. #endif
  440. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.PrimaryKeyEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  441. [TypeConverterAttribute ("System.Data.PrimaryKeyTypeConverter, " + Consts.AssemblySystem_Data)]
  442. public DataColumn[] PrimaryKey {
  443. get {
  444. if (_primaryKeyConstraint == null) {
  445. return new DataColumn[] {};
  446. }
  447. return _primaryKeyConstraint.Columns;
  448. }
  449. set {
  450. if (value == null || value.Length == 0) {
  451. if (_primaryKeyConstraint != null) {
  452. _primaryKeyConstraint.SetIsPrimaryKey (false);
  453. Constraints.Remove(_primaryKeyConstraint);
  454. _primaryKeyConstraint = null;
  455. }
  456. return;
  457. }
  458. if (InitInProgress) {
  459. _latestPrimaryKeyCols = value;
  460. return;
  461. }
  462. // first check if value is the same as current PK.
  463. if (_primaryKeyConstraint!= null && DataColumn.AreColumnSetsTheSame(value, _primaryKeyConstraint.Columns))
  464. return;
  465. //Does constraint exist for these columns
  466. UniqueConstraint uc = UniqueConstraint.GetUniqueConstraintForColumnSet(this.Constraints, (DataColumn[]) value);
  467. //if constraint doesn't exist for columns
  468. //create new unique primary key constraint
  469. if (null == uc) {
  470. foreach (DataColumn Col in (DataColumn[]) value) {
  471. if (Col.Table == null)
  472. break;
  473. if (Columns.IndexOf (Col) < 0)
  474. throw new ArgumentException ("PrimaryKey columns do not belong to this table.");
  475. }
  476. // create constraint with primary key indication set to false
  477. // to avoid recursion
  478. uc = new UniqueConstraint( (DataColumn[]) value, false);
  479. Constraints.Add (uc);
  480. }
  481. //Remove the existing primary key
  482. if (_primaryKeyConstraint != null) {
  483. _primaryKeyConstraint.SetIsPrimaryKey (false);
  484. Constraints.Remove (_primaryKeyConstraint);
  485. _primaryKeyConstraint = null;
  486. }
  487. //set the constraint as the new primary key
  488. UniqueConstraint.SetAsPrimaryKey (Constraints, uc);
  489. _primaryKeyConstraint = uc;
  490. for (int j=0; j < uc.Columns.Length; ++j)
  491. uc.Columns[j].AllowDBNull = false;
  492. }
  493. }
  494. internal UniqueConstraint PrimaryKeyConstraint {
  495. get{
  496. return _primaryKeyConstraint;
  497. }
  498. }
  499. /// <summary>
  500. /// Gets the collection of_rows that belong to this table.
  501. /// </summary>
  502. [Browsable (false)]
  503. #if !NET_2_0
  504. [DataSysDescription ("Indicates the collection that holds the rows of data for this table.")]
  505. #endif
  506. public DataRowCollection Rows {
  507. get { return _rows; }
  508. }
  509. /// <summary>
  510. /// Gets or sets an System.ComponentModel.ISite
  511. /// for the DataTable.
  512. /// </summary>
  513. [Browsable (false)]
  514. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  515. public override ISite Site {
  516. get { return _site; }
  517. set { _site = value; }
  518. }
  519. /// <summary>
  520. /// Gets or sets the name of the the DataTable.
  521. /// </summary>
  522. [DataCategory ("Data")]
  523. #if !NET_2_0
  524. [DataSysDescription ("Indicates the name used to look up this table in the Tables collection of a DataSet.")]
  525. #endif
  526. [DefaultValue ("")]
  527. [RefreshProperties (RefreshProperties.All)]
  528. public string TableName {
  529. get { return _tableName == null ? "" : _tableName; }
  530. set { _tableName = value; }
  531. }
  532. bool IListSource.ContainsListCollection {
  533. get {
  534. // the collection is a DataView
  535. return false;
  536. }
  537. }
  538. internal RecordCache RecordCache {
  539. get {
  540. return _recordCache;
  541. }
  542. }
  543. private DataRowBuilder RowBuilder
  544. {
  545. get
  546. {
  547. // initiate only one row builder.
  548. if (_rowBuilder == null)
  549. _rowBuilder = new DataRowBuilder (this, -1, 0);
  550. else
  551. // new row get id -1.
  552. _rowBuilder._rowId = -1;
  553. return _rowBuilder;
  554. }
  555. }
  556. internal bool EnforceConstraints {
  557. get { return enforceConstraints; }
  558. set {
  559. if (value == enforceConstraints)
  560. return;
  561. if (value) {
  562. // reset indexes since they may be outdated
  563. ResetIndexes();
  564. // assert all constraints
  565. foreach (Constraint constraint in Constraints)
  566. constraint.AssertConstraint();
  567. AssertNotNullConstraints ();
  568. if (HasErrors)
  569. Constraint.ThrowConstraintException ();
  570. }
  571. enforceConstraints = value;
  572. }
  573. }
  574. internal void AssertNotNullConstraints ()
  575. {
  576. if (_duringDataLoad && !_nullConstraintViolationDuringDataLoad)
  577. return;
  578. bool result = false;
  579. String errMsg;
  580. for (int j = 0; j < Rows.Count; j++) {
  581. if (!Rows [j].HasVersion (DataRowVersion.Default))
  582. continue;
  583. errMsg = String.Empty;
  584. for (int i = 0; i < Columns.Count; i++) {
  585. DataColumn column = Columns[i];
  586. if (column.AllowDBNull || !Rows[j].IsNull (column))
  587. continue;
  588. result = true;
  589. errMsg = String.Format("Column '{0}' does not allow DBNull.Value.",
  590. column.ColumnName);
  591. Rows [j].SetColumnError (i, errMsg);
  592. }
  593. // ms.net sets the last ColumnError as RowError
  594. if (errMsg != String.Empty)
  595. Rows [j].RowError = errMsg;
  596. }
  597. if (!result)
  598. _nullConstraintViolationDuringDataLoad = false;
  599. }
  600. internal bool RowsExist(DataColumn[] columns, DataColumn[] relatedColumns,DataRow row)
  601. {
  602. int curIndex = row.IndexFromVersion(DataRowVersion.Default);
  603. int tmpRecord = RecordCache.NewRecord();
  604. try {
  605. for (int i = 0; i < relatedColumns.Length; i++) {
  606. // according to MSDN: the DataType value for both columns must be identical.
  607. columns[i].DataContainer.CopyValue(relatedColumns[i].DataContainer, curIndex, tmpRecord);
  608. }
  609. return RowsExist(columns, tmpRecord);
  610. }
  611. finally {
  612. RecordCache.DisposeRecord(tmpRecord);
  613. }
  614. }
  615. bool RowsExist(DataColumn[] columns, int index)
  616. {
  617. bool rowsExist = false;
  618. Index indx = this.FindIndex(columns);
  619. if (indx != null) { // lookup for a row in index
  620. rowsExist = (indx.Find(index) != -1);
  621. }
  622. else {
  623. // we have to perform full-table scan
  624. // check that there is a parent for this row.
  625. foreach (DataRow thisRow in this.Rows) {
  626. if (thisRow.RowState != DataRowState.Deleted) {
  627. bool match = true;
  628. // check if the values in the columns are equal
  629. int thisIndex = -1;
  630. if (thisRow.RowState == DataRowState.Modified)
  631. thisIndex = thisRow.IndexFromVersion(DataRowVersion.Original);
  632. else
  633. thisIndex = thisRow.IndexFromVersion(DataRowVersion.Current);
  634. foreach (DataColumn column in columns) {
  635. if (column.DataContainer.CompareValues(thisIndex, index) != 0) {
  636. match = false;
  637. break;
  638. }
  639. }
  640. if (match) {// there is a row with columns values equals to those supplied.
  641. rowsExist = true;
  642. break;
  643. }
  644. }
  645. }
  646. }
  647. return rowsExist;
  648. }
  649. /// <summary>
  650. /// Commits all the changes made to this table since the
  651. /// last time AcceptChanges was called.
  652. /// </summary>
  653. public void AcceptChanges ()
  654. {
  655. //FIXME: Do we need to validate anything here or
  656. //try to catch any errors to deal with them?
  657. // we do not use foreach because if one of the rows is in Delete state
  658. // it will be romeved from Rows and we get an exception.
  659. DataRow myRow;
  660. for (int i = 0; i < Rows.Count; )
  661. {
  662. myRow = Rows[i];
  663. myRow.AcceptChanges();
  664. // if the row state is Detached it meens that it was removed from row list (Rows)
  665. // so we should not increase 'i'.
  666. if (myRow.RowState != DataRowState.Detached)
  667. i++;
  668. }
  669. _rows.OnListChanged (this, new ListChangedEventArgs (ListChangedType.Reset, -1, -1));
  670. }
  671. /// <summary>
  672. /// Begins the initialization of a DataTable that is used
  673. /// on a form or used by another component. The initialization
  674. /// occurs at runtime.
  675. /// </summary>
  676. public
  677. #if NET_2_0
  678. virtual
  679. #endif
  680. void BeginInit ()
  681. {
  682. InitInProgress = true;
  683. }
  684. /// <summary>
  685. /// Turns off notifications, index maintenance, and
  686. /// constraints while loading data.
  687. /// </summary>
  688. [MonoTODO]
  689. public void BeginLoadData ()
  690. {
  691. if (!this._duringDataLoad)
  692. {
  693. //duringDataLoad is important to EndLoadData and
  694. //for not throwing unexpected exceptions.
  695. this._duringDataLoad = true;
  696. this._nullConstraintViolationDuringDataLoad = false;
  697. if (this.dataSet != null)
  698. {
  699. //Saving old Enforce constraints state for later
  700. //use in the EndLoadData.
  701. this.dataSetPrevEnforceConstraints = this.dataSet.EnforceConstraints;
  702. this.dataSet.EnforceConstraints = false;
  703. }
  704. else {
  705. //if table does not belong to any data set use EnforceConstraints of the table
  706. this.EnforceConstraints = false;
  707. }
  708. }
  709. return;
  710. }
  711. /// <summary>
  712. /// Clears the DataTable of all data.
  713. /// </summary>
  714. public void Clear () {
  715. // Foriegn key constraints are checked in _rows.Clear method
  716. _rows.Clear ();
  717. foreach(Index index in Indexes)
  718. index.Reset();
  719. #if NET_2_0
  720. OnTableCleared (new DataTableClearEventArgs (this));
  721. #endif // NET_2_0
  722. }
  723. /// <summary>
  724. /// Clones the structure of the DataTable, including
  725. /// all DataTable schemas and constraints.
  726. /// </summary>
  727. public virtual DataTable Clone ()
  728. {
  729. // Use Activator so we can use non-public constructors.
  730. DataTable Copy = (DataTable) Activator.CreateInstance(GetType(), true);
  731. CopyProperties (Copy);
  732. return Copy;
  733. }
  734. /// <summary>
  735. /// Computes the given expression on the current_rows that
  736. /// pass the filter criteria.
  737. /// </summary>
  738. [MonoTODO]
  739. public object Compute (string expression, string filter)
  740. {
  741. // expression is an aggregate function
  742. // filter is an expression used to limit rows
  743. DataRow[] rows = Select(filter);
  744. if (rows == null || rows.Length == 0)
  745. return DBNull.Value;
  746. Parser parser = new Parser (rows);
  747. IExpression expr = parser.Compile (expression);
  748. object obj = expr.Eval (rows[0]);
  749. return obj;
  750. }
  751. /// <summary>
  752. /// Copies both the structure and data for this DataTable.
  753. /// </summary>
  754. public DataTable Copy ()
  755. {
  756. DataTable copy = Clone();
  757. copy._duringDataLoad = true;
  758. foreach (DataRow row in Rows) {
  759. DataRow newRow = copy.NewNotInitializedRow();
  760. copy.Rows.AddInternal(newRow);
  761. CopyRow(row,newRow);
  762. }
  763. copy._duringDataLoad = false;
  764. // rebuild copy indexes after loading all rows
  765. copy.ResetIndexes();
  766. return copy;
  767. }
  768. internal void CopyRow(DataRow fromRow,DataRow toRow)
  769. {
  770. if (fromRow.HasErrors) {
  771. fromRow.CopyErrors(toRow);
  772. }
  773. if (fromRow.HasVersion(DataRowVersion.Original)) {
  774. toRow.Original = toRow.Table.RecordCache.CopyRecord(this,fromRow.Original,-1);
  775. }
  776. if (fromRow.HasVersion(DataRowVersion.Current)) {
  777. if (fromRow.Original != fromRow.Current) {
  778. toRow.Current = toRow.Table.RecordCache.CopyRecord(this,fromRow.Current,-1);
  779. }
  780. else {
  781. toRow.Current = toRow.Original;
  782. }
  783. }
  784. }
  785. private void CopyProperties (DataTable Copy)
  786. {
  787. Copy.CaseSensitive = CaseSensitive;
  788. Copy._virginCaseSensitive = _virginCaseSensitive;
  789. // Copy.ChildRelations
  790. // Copy.Constraints
  791. // Copy.Container
  792. // Copy.DefaultView
  793. // Copy.DesignMode
  794. Copy.DisplayExpression = DisplayExpression;
  795. if(ExtendedProperties.Count > 0) {
  796. // Cannot copy extended properties directly as the property does not have a set accessor
  797. Array tgtArray = Array.CreateInstance( typeof (object), ExtendedProperties.Count);
  798. ExtendedProperties.Keys.CopyTo (tgtArray, 0);
  799. for (int i=0; i < ExtendedProperties.Count; i++)
  800. Copy.ExtendedProperties.Add (tgtArray.GetValue (i), ExtendedProperties[tgtArray.GetValue (i)]);
  801. }
  802. Copy.Locale = Locale;
  803. Copy.MinimumCapacity = MinimumCapacity;
  804. Copy.Namespace = Namespace;
  805. // Copy.ParentRelations
  806. Copy.Prefix = Prefix;
  807. Copy.Site = Site;
  808. Copy.TableName = TableName;
  809. bool isEmpty = Copy.Columns.Count == 0;
  810. // Copy columns
  811. foreach (DataColumn column in Columns) {
  812. // When cloning a table, the columns may be added in the default constructor.
  813. if (isEmpty || !Copy.Columns.Contains(column.ColumnName)) {
  814. Copy.Columns.Add (column.Clone());
  815. }
  816. }
  817. CopyConstraints(Copy);
  818. // add primary key to the copy
  819. if (PrimaryKey.Length > 0) {
  820. DataColumn[] pColumns = new DataColumn[PrimaryKey.Length];
  821. for (int i = 0; i < pColumns.Length; i++)
  822. pColumns[i] = Copy.Columns[PrimaryKey[i].ColumnName];
  823. Copy.PrimaryKey = pColumns;
  824. }
  825. }
  826. private void CopyConstraints(DataTable copy)
  827. {
  828. UniqueConstraint origUc;
  829. UniqueConstraint copyUc;
  830. for (int i = 0; i < this.Constraints.Count; i++)
  831. {
  832. if (this.Constraints[i] is UniqueConstraint)
  833. {
  834. // typed ds can already contain the constraints
  835. if (copy.Constraints.Contains (this.Constraints [i].ConstraintName))
  836. continue;
  837. origUc = (UniqueConstraint)this.Constraints[i];
  838. DataColumn[] columns = new DataColumn[origUc.Columns.Length];
  839. for (int j = 0; j < columns.Length; j++)
  840. columns[j] = copy.Columns[origUc.Columns[j].ColumnName];
  841. copyUc = new UniqueConstraint(origUc.ConstraintName, columns, origUc.IsPrimaryKey);
  842. copy.Constraints.Add(copyUc);
  843. }
  844. }
  845. }
  846. /// <summary>
  847. /// Ends the initialization of a DataTable that is used
  848. /// on a form or used by another component. The
  849. /// initialization occurs at runtime.
  850. /// </summary>
  851. [MonoTODO]
  852. public
  853. #if NET_2_0
  854. virtual
  855. #endif
  856. void EndInit ()
  857. {
  858. InitInProgress = false;
  859. FinishInit ();
  860. }
  861. internal bool InitInProgress {
  862. get { return fInitInProgress; }
  863. set { fInitInProgress = value; }
  864. }
  865. internal void FinishInit ()
  866. {
  867. UniqueConstraint oldPK = _primaryKeyConstraint;
  868. // Columns shud be added 'before' the constraints
  869. Columns.PostAddRange ();
  870. // Add the constraints
  871. _constraintCollection.PostAddRange ();
  872. // ms.net behavior : If a PrimaryKey (UniqueConstraint) is added thru AddRange,
  873. // then it takes precedence over an direct assignment of PrimaryKey
  874. if (_primaryKeyConstraint == oldPK)
  875. PrimaryKey = _latestPrimaryKeyCols;
  876. }
  877. /// <summary>
  878. /// Turns on notifications, index maintenance, and
  879. /// constraints after loading data.
  880. /// </summary>
  881. public void EndLoadData()
  882. {
  883. if (this._duringDataLoad) {
  884. //Getting back to previous EnforceConstraint state
  885. if (this.dataSet != null)
  886. this.dataSet.InternalEnforceConstraints(this.dataSetPrevEnforceConstraints,true);
  887. else
  888. this.EnforceConstraints = true;
  889. this._duringDataLoad = false;
  890. }
  891. }
  892. /// <summary>
  893. /// Gets a copy of the DataTable that contains all
  894. /// changes made to it since it was loaded or
  895. /// AcceptChanges was last called.
  896. /// </summary>
  897. public DataTable GetChanges()
  898. {
  899. return GetChanges(DataRowState.Added | DataRowState.Deleted | DataRowState.Modified);
  900. }
  901. /// <summary>
  902. /// Gets a copy of the DataTable containing all
  903. /// changes made to it since it was last loaded, or
  904. /// since AcceptChanges was called, filtered by DataRowState.
  905. /// </summary>
  906. public DataTable GetChanges(DataRowState rowStates)
  907. {
  908. DataTable copyTable = null;
  909. IEnumerator rowEnumerator = Rows.GetEnumerator();
  910. while (rowEnumerator.MoveNext()) {
  911. DataRow row = (DataRow)rowEnumerator.Current;
  912. // The spec says relationship constraints may cause Unchanged parent rows to be included but
  913. // MS .NET 1.1 does not include Unchanged rows even if their child rows are changed.
  914. if (row.IsRowChanged(rowStates)) {
  915. if (copyTable == null)
  916. copyTable = Clone();
  917. DataRow newRow = copyTable.NewNotInitializedRow();
  918. row.CopyValuesToRow(newRow);
  919. copyTable.Rows.AddInternal (newRow);
  920. }
  921. }
  922. return copyTable;
  923. }
  924. #if NET_2_0
  925. [MonoTODO]
  926. public DataTableReader CreateDataReader ()
  927. {
  928. return new DataTableReader (this);
  929. }
  930. #endif
  931. /// <summary>
  932. /// Gets an array of DataRow objects that contain errors.
  933. /// </summary>
  934. public DataRow[] GetErrors ()
  935. {
  936. ArrayList errors = new ArrayList();
  937. for (int i = 0; i < _rows.Count; i++)
  938. {
  939. if (_rows[i].HasErrors)
  940. errors.Add(_rows[i]);
  941. }
  942. DataRow[] ret = NewRowArray(errors.Count);
  943. errors.CopyTo(ret, 0);
  944. return ret;
  945. }
  946. /// <summary>
  947. /// This member is only meant to support Mono's infrastructure
  948. /// </summary>
  949. protected virtual DataTable CreateInstance ()
  950. {
  951. return Activator.CreateInstance (this.GetType (), true) as DataTable;
  952. }
  953. /// <summary>
  954. /// This member is only meant to support Mono's infrastructure
  955. /// </summary>
  956. protected virtual Type GetRowType ()
  957. {
  958. return typeof (DataRow);
  959. }
  960. /// <summary>
  961. /// This member is only meant to support Mono's infrastructure
  962. ///
  963. /// Used for Data Binding between System.Web.UI. controls
  964. /// like a DataGrid
  965. /// or
  966. /// System.Windows.Forms controls like a DataGrid
  967. /// </summary>
  968. IList IListSource.GetList ()
  969. {
  970. IList list = (IList) DefaultView;
  971. return list;
  972. }
  973. /// <summary>
  974. /// Copies a DataRow into a DataTable, preserving any
  975. /// property settings, as well as original and current values.
  976. /// </summary>
  977. public void ImportRow (DataRow row)
  978. {
  979. if (row.RowState == DataRowState.Detached)
  980. return;
  981. DataRow newRow = NewNotInitializedRow();
  982. int original = -1;
  983. if (row.HasVersion(DataRowVersion.Original)) {
  984. original = row.IndexFromVersion(DataRowVersion.Original);
  985. newRow.Original = RecordCache.NewRecord();
  986. RecordCache.CopyRecord(row.Table,original,newRow.Original);
  987. }
  988. if (row.HasVersion(DataRowVersion.Current)) {
  989. int current = row.IndexFromVersion(DataRowVersion.Current);
  990. if (current == original)
  991. newRow.Current = newRow.Original;
  992. else {
  993. newRow.Current = RecordCache.NewRecord();
  994. RecordCache.CopyRecord(row.Table,current,newRow.Current);
  995. }
  996. }
  997. //Import the row only if RowState is not detached
  998. //Validation for Deleted Rows happens during Accept/RejectChanges
  999. if (row.RowState != DataRowState.Deleted)
  1000. newRow.Validate();
  1001. else
  1002. AddRowToIndexes (newRow);
  1003. Rows.AddInternal(newRow);
  1004. if (row.HasErrors) {
  1005. row.CopyErrors(newRow);
  1006. }
  1007. }
  1008. internal int DefaultValuesRowIndex
  1009. {
  1010. get {
  1011. return _defaultValuesRowIndex;
  1012. }
  1013. }
  1014. /// <summary>
  1015. /// This member is only meant to support Mono's infrastructure
  1016. /// </summary>
  1017. void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
  1018. {
  1019. DataSet dset;
  1020. if (dataSet != null)
  1021. dset = dataSet;
  1022. else {
  1023. dset = new DataSet ("tmpDataSet");
  1024. dset.Tables.Add (this);
  1025. }
  1026. StringWriter sw = new StringWriter ();
  1027. XmlTextWriter tw = new XmlTextWriter (sw);
  1028. tw.Formatting = Formatting.Indented;
  1029. dset.WriteIndividualTableContent (tw, this, XmlWriteMode.DiffGram);
  1030. tw.Close ();
  1031. StringWriter sw2 = new StringWriter ();
  1032. DataTableCollection tables = new DataTableCollection (dset);
  1033. tables.Add (this);
  1034. XmlSchemaWriter.WriteXmlSchema (dset, new XmlTextWriter (sw2), tables, null);
  1035. sw2.Close ();
  1036. info.AddValue ("XmlSchema", sw2.ToString(), typeof(string));
  1037. info.AddValue ("XmlDiffGram", sw.ToString(), typeof(string));
  1038. }
  1039. #if NET_2_0
  1040. /// <summary>
  1041. /// Loads the table with the values from the reader
  1042. /// </summary>
  1043. public void Load (IDataReader reader)
  1044. {
  1045. Load (reader, LoadOption.PreserveChanges);
  1046. }
  1047. /// <summary>
  1048. /// Loads the table with the values from the reader and the pattern
  1049. /// of the changes to the existing rows or the new rows are based on
  1050. /// the LoadOption passed.
  1051. /// </summary>
  1052. public void Load (IDataReader reader, LoadOption loadOption)
  1053. {
  1054. bool prevEnforceConstr = this.EnforceConstraints;
  1055. try {
  1056. this.EnforceConstraints = false;
  1057. int [] mapping = DbDataAdapter.BuildSchema (reader, this, SchemaType.Mapped,
  1058. MissingSchemaAction.AddWithKey,
  1059. MissingMappingAction.Passthrough,
  1060. new DataTableMappingCollection ());
  1061. DbDataAdapter.FillFromReader (this,
  1062. reader,
  1063. 0, // start from
  1064. 0, // all records
  1065. mapping,
  1066. loadOption);
  1067. } finally {
  1068. this.EnforceConstraints = prevEnforceConstr;
  1069. }
  1070. }
  1071. #endif
  1072. /// <summary>
  1073. /// Finds and updates a specific row. If no matching row
  1074. /// is found, a new row is created using the given values.
  1075. /// </summary>
  1076. public DataRow LoadDataRow (object[] values, bool fAcceptChanges)
  1077. {
  1078. DataRow row = null;
  1079. if (PrimaryKey.Length == 0)
  1080. row = Rows.Add (values);
  1081. else {
  1082. EnsureDefaultValueRowIndex();
  1083. int newRecord = CreateRecord(values);
  1084. int existingRecord = _primaryKeyConstraint.Index.Find (newRecord);
  1085. if (existingRecord < 0) {
  1086. row = NewRowFromBuilder (RowBuilder);
  1087. row.Proposed = newRecord;
  1088. Rows.AddInternal(row);
  1089. if (!_duringDataLoad)
  1090. AddRowToIndexes (row);
  1091. } else {
  1092. row = RecordCache[existingRecord];
  1093. row.BeginEdit();
  1094. row.ImportRecord(newRecord);
  1095. row.EndEdit();
  1096. }
  1097. }
  1098. if (fAcceptChanges)
  1099. row.AcceptChanges ();
  1100. return row;
  1101. }
  1102. internal DataRow LoadDataRow (IDataRecord record, int[] mapping, int length, bool fAcceptChanges)
  1103. {
  1104. DataRow row = null;
  1105. int tmpRecord = this.RecordCache.NewRecord ();
  1106. try {
  1107. RecordCache.ReadIDataRecord (tmpRecord,record,mapping,length);
  1108. if (PrimaryKey.Length != 0) {
  1109. bool hasPrimaryValues = true;
  1110. foreach(DataColumn col in PrimaryKey) {
  1111. if(!(col.Ordinal < mapping.Length)) {
  1112. hasPrimaryValues = false;
  1113. break;
  1114. }
  1115. }
  1116. if (hasPrimaryValues) {
  1117. int existingRecord = _primaryKeyConstraint.Index.Find (tmpRecord);
  1118. if (existingRecord != -1)
  1119. row = RecordCache [existingRecord];
  1120. }
  1121. }
  1122. if (row == null) {
  1123. row = NewNotInitializedRow();
  1124. row.Proposed = tmpRecord;
  1125. Rows.AddInternal (row);
  1126. } else {
  1127. row.BeginEdit ();
  1128. row.ImportRecord (tmpRecord);
  1129. row.EndEdit ();
  1130. }
  1131. if (fAcceptChanges)
  1132. row.AcceptChanges();
  1133. } catch(Exception e) {
  1134. this.RecordCache.DisposeRecord(tmpRecord);
  1135. throw e;
  1136. }
  1137. return row;
  1138. }
  1139. #if NET_2_0
  1140. /// <summary>
  1141. /// Loads the given values into an existing row if matches or creates
  1142. /// the new row popluated with the values.
  1143. /// </summary>
  1144. /// <remarks>
  1145. /// This method searches for the values using primary keys and it first
  1146. /// searches using the original values of the rows and if not found, it
  1147. /// searches using the current version of the row.
  1148. /// </remarks>
  1149. public DataRow LoadDataRow (object [] values, LoadOption loadOption)
  1150. {
  1151. DataRow row = null;
  1152. // Find Data DataRow
  1153. if (this.PrimaryKey.Length > 0) {
  1154. object [] keys = new object [PrimaryKey.Length];
  1155. for (int i=0; i < PrimaryKey.Length; i++)
  1156. keys [i] = values [PrimaryKey [i].Ordinal];
  1157. row = Rows.Find(keys, DataViewRowState.OriginalRows);
  1158. if (row == null)
  1159. row = Rows.Find (keys);
  1160. }
  1161. // If not found, add new row
  1162. if (row == null
  1163. || (row.RowState == DataRowState.Deleted
  1164. && loadOption == LoadOption.Upsert)) {
  1165. row = NewNotInitializedRow ();
  1166. row.ImportRecord (CreateRecord(values));
  1167. row.Validate(); // this adds to index ;-)
  1168. if (loadOption == LoadOption.OverwriteChanges ||
  1169. loadOption == LoadOption.PreserveChanges) {
  1170. Rows.AddInternal(row);
  1171. ChangingDataRow (row, DataRowAction.ChangeCurrentAndOriginal);
  1172. row.Original = row.Current;
  1173. ChangedDataRow (row, DataRowAction.ChangeCurrentAndOriginal);
  1174. } else
  1175. Rows.AddInternal(row);
  1176. return row;
  1177. }
  1178. if (row.RowState == DataRowState.Deleted
  1179. && loadOption == LoadOption.OverwriteChanges)
  1180. row.RejectChanges ();
  1181. row.Load (values, loadOption);
  1182. return row;
  1183. }
  1184. [MonoTODO]
  1185. public void Merge (DataTable table)
  1186. {
  1187. Merge (table, false, MissingSchemaAction.Add);
  1188. }
  1189. [MonoTODO]
  1190. public void Merge (DataTable table, bool preserveChanges)
  1191. {
  1192. Merge (table, preserveChanges, MissingSchemaAction.Add);
  1193. }
  1194. [MonoTODO]
  1195. public void Merge (DataTable table, bool preserveChanges, MissingSchemaAction missingSchemaAction)
  1196. {
  1197. MergeManager.Merge (this, table, preserveChanges, missingSchemaAction);
  1198. }
  1199. #endif
  1200. /// <summary>
  1201. /// Creates a new DataRow with the same schema as the table.
  1202. /// </summary>
  1203. public DataRow NewRow ()
  1204. {
  1205. EnsureDefaultValueRowIndex();
  1206. DataRow newRow = NewRowFromBuilder (RowBuilder);
  1207. newRow.Proposed = CreateRecord(null);
  1208. return newRow;
  1209. }
  1210. internal int CreateRecord(object[] values) {
  1211. int valCount = values != null ? values.Length : 0;
  1212. if (valCount > Columns.Count)
  1213. throw new ArgumentException("Input array is longer than the number of columns in this table.");
  1214. int index = RecordCache.NewRecord();
  1215. try {
  1216. for (int i = 0; i < valCount; i++) {
  1217. object value = values[i];
  1218. if (value == null)
  1219. Columns[i].SetDefaultValue(index);
  1220. else
  1221. Columns[i][index] = values[i];
  1222. }
  1223. for(int i = valCount; i < Columns.Count; i++) {
  1224. Columns[i].SetDefaultValue(index);
  1225. }
  1226. return index;
  1227. }
  1228. catch {
  1229. RecordCache.DisposeRecord(index);
  1230. throw;
  1231. }
  1232. }
  1233. private void EnsureDefaultValueRowIndex()
  1234. {
  1235. // initialize default values row for the first time
  1236. if ( _defaultValuesRowIndex == -1 ) {
  1237. _defaultValuesRowIndex = RecordCache.NewRecord();
  1238. foreach(DataColumn column in Columns) {
  1239. column.DataContainer[_defaultValuesRowIndex] = column.DefaultValue;
  1240. }
  1241. }
  1242. }
  1243. #if NET_2_0
  1244. internal int CompareRecords(int x, int y) {
  1245. for (int col = 0; col < Columns.Count; col++) {
  1246. int res = Columns[col].DataContainer.CompareValues (x, y);
  1247. if (res != 0)
  1248. return res;
  1249. }
  1250. return 0;
  1251. }
  1252. #endif
  1253. /// <summary>
  1254. /// This member supports the .NET Framework infrastructure
  1255. /// and is not intended to be used directly from your code.
  1256. /// </summary>
  1257. protected internal DataRow[] NewRowArray (int size)
  1258. {
  1259. return (DataRow[]) Array.CreateInstance (GetRowType (), size);
  1260. }
  1261. /// <summary>
  1262. /// Creates a new row from an existing row.
  1263. /// </summary>
  1264. protected virtual DataRow NewRowFromBuilder (DataRowBuilder builder)
  1265. {
  1266. return new DataRow (builder);
  1267. }
  1268. internal DataRow NewNotInitializedRow()
  1269. {
  1270. EnsureDefaultValueRowIndex();
  1271. return NewRowFromBuilder (RowBuilder);
  1272. }
  1273. #if NET_2_0
  1274. [MonoTODO]
  1275. XmlReadMode ReadXml (Stream stream)
  1276. {
  1277. throw new NotImplementedException ();
  1278. }
  1279. public void ReadXmlSchema (Stream stream)
  1280. {
  1281. ReadXmlSchema (new XmlTextReader (stream));
  1282. }
  1283. public void ReadXmlSchema (TextReader reader)
  1284. {
  1285. ReadXmlSchema (new XmlTextReader (reader));
  1286. }
  1287. public void ReadXmlSchema (string fileName)
  1288. {
  1289. XmlTextReader reader = null;
  1290. try {
  1291. reader = new XmlTextReader (fileName);
  1292. ReadXmlSchema (reader);
  1293. } finally {
  1294. if (reader != null)
  1295. reader.Close ();
  1296. }
  1297. }
  1298. public void ReadXmlSchema (XmlReader reader)
  1299. {
  1300. DataSet ds = new DataSet ();
  1301. new XmlSchemaDataImporter (ds, reader).Process ();
  1302. DataTable target = null;
  1303. if (TableName == String.Empty) {
  1304. if (ds.Tables.Count > 0)
  1305. target = ds.Tables [0];
  1306. }
  1307. else {
  1308. target = ds.Tables [TableName];
  1309. if (target == null)
  1310. throw new ArgumentException (String.Format ("DataTable '{0}' does not match to any DataTable in source.", TableName));
  1311. }
  1312. if (target != null)
  1313. target.CopyProperties (this);
  1314. }
  1315. #endif
  1316. /// <summary>
  1317. /// Rolls back all changes that have been made to the
  1318. /// table since it was loaded, or the last time AcceptChanges
  1319. /// was called.
  1320. /// </summary>
  1321. public void RejectChanges ()
  1322. {
  1323. for (int i = _rows.Count - 1; i >= 0; i--) {
  1324. DataRow row = _rows [i];
  1325. if (row.RowState != DataRowState.Unchanged)
  1326. _rows [i].RejectChanges ();
  1327. }
  1328. }
  1329. /// <summary>
  1330. /// Resets the DataTable to its original state.
  1331. /// </summary>
  1332. public virtual void Reset ()
  1333. {
  1334. Clear();
  1335. while (ParentRelations.Count > 0)
  1336. {
  1337. if (dataSet.Relations.Contains(ParentRelations[ParentRelations.Count - 1].RelationName))
  1338. dataSet.Relations.Remove(ParentRelations[ParentRelations.Count - 1]);
  1339. }
  1340. while (ChildRelations.Count > 0)
  1341. {
  1342. if (dataSet.Relations.Contains(ChildRelations[ChildRelations.Count - 1].RelationName))
  1343. dataSet.Relations.Remove(ChildRelations[ChildRelations.Count - 1]);
  1344. }
  1345. Constraints.Clear();
  1346. Columns.Clear();
  1347. }
  1348. /// <summary>
  1349. /// Gets an array of all DataRow objects.
  1350. /// </summary>
  1351. public DataRow[] Select ()
  1352. {
  1353. return Select(String.Empty, String.Empty, DataViewRowState.CurrentRows);
  1354. }
  1355. /// <summary>
  1356. /// Gets an array of all DataRow objects that match
  1357. /// the filter criteria in order of primary key (or
  1358. /// lacking one, order of addition.)
  1359. /// </summary>
  1360. public DataRow[] Select (string filterExpression)
  1361. {
  1362. return Select(filterExpression, String.Empty, DataViewRowState.CurrentRows);
  1363. }
  1364. /// <summary>
  1365. /// Gets an array of all DataRow objects that
  1366. /// match the filter criteria, in the the
  1367. /// specified sort order.
  1368. /// </summary>
  1369. public DataRow[] Select (string filterExpression, string sort)
  1370. {
  1371. return Select(filterExpression, sort, DataViewRowState.CurrentRows);
  1372. }
  1373. /// <summary>
  1374. /// Gets an array of all DataRow objects that match
  1375. /// the filter in the order of the sort, that match
  1376. /// the specified state.
  1377. /// </summary>
  1378. [MonoTODO]
  1379. public DataRow[] Select(string filterExpression, string sort, DataViewRowState recordStates)
  1380. {
  1381. if (filterExpression == null)
  1382. filterExpression = String.Empty;
  1383. IExpression filter = null;
  1384. if (filterExpression != String.Empty) {
  1385. Parser parser = new Parser ();
  1386. filter = parser.Compile (filterExpression);
  1387. }
  1388. DataColumn[] columns = _emptyColumnArray;
  1389. ListSortDirection[] sorts = null;
  1390. if (sort != null && !sort.Equals(String.Empty))
  1391. columns = ParseSortString (this, sort, out sorts, false);
  1392. if (Rows.Count == 0)
  1393. return new DataRow [0];
  1394. //if sort order is not given, sort it in Ascending order of the
  1395. //columns involved in the filter
  1396. if (columns.Length ==0 && filter != null) {
  1397. ArrayList list = new ArrayList ();
  1398. for (int i=0, j=0; i < Columns.Count; ++i) {
  1399. if (!filter.DependsOn (Columns [i]))
  1400. continue;
  1401. list.Add (Columns [i]);
  1402. }
  1403. columns = (DataColumn[])list.ToArray (typeof (DataColumn));
  1404. }
  1405. bool addIndex = true;
  1406. if (filterExpression != String.Empty)
  1407. addIndex = false;
  1408. Index index = GetIndex(columns, sorts, recordStates, filter, false, addIndex);
  1409. int[] records = index.GetAll();
  1410. DataRow[] dataRows = NewRowArray(index.Size);
  1411. for (int i = 0; i < dataRows.Length; i++)
  1412. dataRows[i] = RecordCache[records[i]];
  1413. return dataRows;
  1414. }
  1415. private void AddIndex (Index index)
  1416. {
  1417. if (_indexes == null) {
  1418. _indexes = new ArrayList();
  1419. }
  1420. _indexes.Add (index);
  1421. }
  1422. /// <summary>
  1423. /// Returns index corresponding to columns,sort,row state filter and unique values given.
  1424. /// If such an index not exists, creates a new one.
  1425. /// </summary>
  1426. /// <param name="columns">Columns set of the index to look for.</param>
  1427. /// <param name="sort">Columns sort order of the index to look for.</param>
  1428. /// <param name="rowState">Rpw state filter of the index to look for.</param>
  1429. /// <param name="unique">Uniqueness of the index to look for.</param>
  1430. /// <param name="strict">Indicates whenever the index found should correspond in its uniquness to the value of unique parameter specified.</param>
  1431. /// <param name="reset">Indicates whenever the already existing index should be forced to reset.</param>
  1432. /// <returns></returns>
  1433. internal Index GetIndex(DataColumn[] columns, ListSortDirection[] sort, DataViewRowState rowState, IExpression filter, bool reset)
  1434. {
  1435. Index index = FindIndex(columns,sort,rowState,filter);
  1436. if (index == null ) {
  1437. index = new Index(new Key(this,columns,sort,rowState,filter));
  1438. AddIndex(index);
  1439. }
  1440. else if (reset) {
  1441. // reset existing index only if asked for this
  1442. index.Reset();
  1443. }
  1444. return index;
  1445. }
  1446. internal Index GetIndex (DataColumn[] columns, ListSortDirection[] sort,
  1447. DataViewRowState rowState, IExpression filter,
  1448. bool reset, bool addIndex)
  1449. {
  1450. Index index = FindIndex(columns,sort,rowState,filter);
  1451. if (index == null ) {
  1452. index = new Index(new Key(this,columns,sort,rowState,filter));
  1453. if (addIndex)
  1454. AddIndex (index);
  1455. }
  1456. else if (reset) {
  1457. // reset existing index only if asked for this
  1458. index.Reset ();
  1459. }
  1460. return index;
  1461. }
  1462. internal Index FindIndex(DataColumn[] columns)
  1463. {
  1464. return FindIndex(columns,null,DataViewRowState.None, null);
  1465. }
  1466. internal Index FindIndex(DataColumn[] columns, ListSortDirection[] sort, DataViewRowState rowState, IExpression filter)
  1467. {
  1468. if (Indexes != null) {
  1469. foreach (Index index in Indexes) {
  1470. if (index.Key.Equals(columns,sort,rowState, filter)) {
  1471. return index;
  1472. }
  1473. }
  1474. }
  1475. return null;
  1476. }
  1477. internal void ResetIndexes()
  1478. {
  1479. foreach(Index index in Indexes) {
  1480. index.Reset();
  1481. }
  1482. }
  1483. internal void ResetCaseSensitiveIndexes()
  1484. {
  1485. foreach(Index index in Indexes) {
  1486. bool containsStringcolumns = false;
  1487. foreach(DataColumn column in index.Key.Columns) {
  1488. if (column.DataType == typeof(string)) {
  1489. containsStringcolumns = true;
  1490. break;
  1491. }
  1492. }
  1493. if (!containsStringcolumns && index.Key.HasFilter)
  1494. foreach (DataColumn column in Columns)
  1495. if ((column.DataType == DbTypes.TypeOfString) && (index.Key.DependsOn (column))) {
  1496. containsStringcolumns = true;
  1497. break;
  1498. }
  1499. if (containsStringcolumns) {
  1500. index.Reset();
  1501. }
  1502. }
  1503. }
  1504. internal void DropIndex(Index index)
  1505. {
  1506. if (index != null && index.RefCount == 0) {
  1507. _indexes.Remove(index);
  1508. }
  1509. }
  1510. internal void DropReferencedIndexes (DataColumn column)
  1511. {
  1512. if (_indexes != null)
  1513. for (int i = _indexes.Count - 1; i >= 0; i--) {
  1514. Index indx = (Index)_indexes [i];
  1515. if (indx.Key.DependsOn (column))
  1516. _indexes.Remove (indx);
  1517. }
  1518. }
  1519. internal void AddRowToIndexes (DataRow row) {
  1520. if (_indexes != null) {
  1521. foreach (Index indx in _indexes) {
  1522. indx.Add (row);
  1523. }
  1524. }
  1525. }
  1526. internal void DeleteRowFromIndexes (DataRow row)
  1527. {
  1528. if (_indexes != null) {
  1529. foreach (Index indx in _indexes) {
  1530. indx.Delete (row);
  1531. }
  1532. }
  1533. }
  1534. /// <summary>
  1535. /// Gets the TableName and DisplayExpression, if
  1536. /// there is one as a concatenated string.
  1537. /// </summary>
  1538. public override string ToString()
  1539. {
  1540. //LAMESPEC: spec says concat the two. impl puts a
  1541. //plus sign infront of DisplayExpression
  1542. string retVal = TableName;
  1543. if(DisplayExpression != null && DisplayExpression != "")
  1544. retVal += " + " + DisplayExpression;
  1545. return retVal;
  1546. }
  1547. #if NET_2_0
  1548. private XmlWriterSettings GetWriterSettings ()
  1549. {
  1550. XmlWriterSettings s = new XmlWriterSettings ();
  1551. s.Indent = true;
  1552. return s;
  1553. }
  1554. public void WriteXml (Stream stream)
  1555. {
  1556. WriteXml (stream, XmlWriteMode.IgnoreSchema);
  1557. }
  1558. public void WriteXml (TextWriter writer)
  1559. {
  1560. WriteXml (writer, XmlWriteMode.IgnoreSchema);
  1561. }
  1562. public void WriteXml (XmlWriter writer)
  1563. {
  1564. WriteXml (writer, XmlWriteMode.IgnoreSchema);
  1565. }
  1566. public void WriteXml (string fileName)
  1567. {
  1568. WriteXml (fileName, XmlWriteMode.IgnoreSchema);
  1569. }
  1570. public void WriteXml (Stream stream, XmlWriteMode mode)
  1571. {
  1572. WriteXml (XmlWriter.Create (stream, GetWriterSettings ()), mode);
  1573. }
  1574. public void WriteXml (TextWriter writer, XmlWriteMode mode)
  1575. {
  1576. WriteXml (XmlWriter.Create (writer, GetWriterSettings ()), mode);
  1577. }
  1578. [MonoTODO]
  1579. public void WriteXml (XmlWriter writer, XmlWriteMode mode)
  1580. {
  1581. throw new NotImplementedException ();
  1582. }
  1583. public void WriteXml (string fileName, XmlWriteMode mode)
  1584. {
  1585. XmlWriter xw = null;
  1586. try {
  1587. xw = XmlWriter.Create (fileName, GetWriterSettings ());
  1588. WriteXml (xw, mode);
  1589. } finally {
  1590. if (xw != null)
  1591. xw.Close ();
  1592. }
  1593. }
  1594. public void WriteXmlSchema (Stream stream)
  1595. {
  1596. WriteXmlSchema (XmlWriter.Create (stream, GetWriterSettings ()));
  1597. }
  1598. public void WriteXmlSchema (TextWriter writer)
  1599. {
  1600. WriteXmlSchema (XmlWriter.Create (writer, GetWriterSettings ()));
  1601. }
  1602. public void WriteXmlSchema (XmlWriter writer)
  1603. {
  1604. DataSet ds = DataSet;
  1605. DataSet tmp = null;
  1606. try {
  1607. if (ds == null) {
  1608. tmp = ds = new DataSet ();
  1609. ds.Tables.Add (this);
  1610. }
  1611. DataTableCollection col = new DataTableCollection (ds);
  1612. col.Add (this);
  1613. XmlSchemaWriter.WriteXmlSchema (ds, writer, col, null);
  1614. } finally {
  1615. if (tmp != null)
  1616. ds.Tables.Remove (this);
  1617. }
  1618. }
  1619. public void WriteXmlSchema (string fileName)
  1620. {
  1621. XmlWriter xw = null;
  1622. try {
  1623. xw = XmlWriter.Create (fileName, GetWriterSettings ());
  1624. WriteXmlSchema (xw);
  1625. } finally {
  1626. if (xw != null)
  1627. xw.Close ();
  1628. }
  1629. }
  1630. #endif
  1631. #region Events
  1632. /// <summary>
  1633. /// Raises the ColumnChanged event.
  1634. /// </summary>
  1635. protected virtual void OnColumnChanged (DataColumnChangeEventArgs e) {
  1636. if (null != ColumnChanged) {
  1637. ColumnChanged (this, e);
  1638. }
  1639. }
  1640. internal void RaiseOnColumnChanged (DataColumnChangeEventArgs e) {
  1641. OnColumnChanged(e);
  1642. }
  1643. #if NET_2_0
  1644. /// <summary>
  1645. /// Raises TableCleared Event and delegates to subscribers
  1646. /// </summary>
  1647. protected virtual void OnTableCleared (DataTableClearEventArgs e) {
  1648. if (TableCleared != null)
  1649. TableCleared (this, e);
  1650. }
  1651. #endif // NET_2_0
  1652. /// <summary>
  1653. /// Raises the ColumnChanging event.
  1654. /// </summary>
  1655. protected virtual void OnColumnChanging (DataColumnChangeEventArgs e) {
  1656. if (null != ColumnChanging) {
  1657. ColumnChanging (this, e);
  1658. }
  1659. }
  1660. internal void RaiseOnColumnChanging (DataColumnChangeEventArgs e) {
  1661. OnColumnChanging(e);
  1662. }
  1663. /// <summary>
  1664. /// Raises the PropertyChanging event.
  1665. /// </summary>
  1666. [MonoTODO]
  1667. protected internal virtual void OnPropertyChanging (PropertyChangedEventArgs pcevent) {
  1668. // if (null != PropertyChanging)
  1669. // {
  1670. // PropertyChanging (this, e);
  1671. // }
  1672. }
  1673. /// <summary>
  1674. /// Notifies the DataTable that a DataColumn is being removed.
  1675. /// </summary>
  1676. protected internal virtual void OnRemoveColumn (DataColumn column) {
  1677. DropReferencedIndexes (column);
  1678. }
  1679. /// <summary>
  1680. /// Raises the RowChanged event.
  1681. /// </summary>
  1682. protected virtual void OnRowChanged (DataRowChangeEventArgs e) {
  1683. if (null != RowChanged) {
  1684. RowChanged(this, e);
  1685. }
  1686. }
  1687. /// <summary>
  1688. /// Raises the RowChanging event.
  1689. /// </summary>
  1690. protected virtual void OnRowChanging (DataRowChangeEventArgs e) {
  1691. if (null != RowChanging) {
  1692. RowChanging(this, e);
  1693. }
  1694. }
  1695. /// <summary>
  1696. /// Raises the RowDeleted event.
  1697. /// </summary>
  1698. protected virtual void OnRowDeleted (DataRowChangeEventArgs e) {
  1699. if (null != RowDeleted) {
  1700. RowDeleted(this, e);
  1701. }
  1702. }
  1703. /// <summary>
  1704. /// Raises the RowDeleting event.
  1705. /// </summary>
  1706. protected virtual void OnRowDeleting (DataRowChangeEventArgs e) {
  1707. if (null != RowDeleting) {
  1708. RowDeleting(this, e);
  1709. }
  1710. }
  1711. /// <summary>
  1712. /// Occurs when after a value has been changed for
  1713. /// the specified DataColumn in a DataRow.
  1714. /// </summary>
  1715. [DataCategory ("Data")]
  1716. #if !NET_2_0
  1717. [DataSysDescription ("Occurs when a value has been changed for this column.")]
  1718. #endif
  1719. public event DataColumnChangeEventHandler ColumnChanged;
  1720. /// <summary>
  1721. /// Occurs when a value is being changed for the specified
  1722. /// DataColumn in a DataRow.
  1723. /// </summary>
  1724. [DataCategory ("Data")]
  1725. #if !NET_2_0
  1726. [DataSysDescription ("Occurs when a value has been submitted for this column. The user can modify the proposed value and should throw an exception to cancel the edit.")]
  1727. #endif
  1728. public event DataColumnChangeEventHandler ColumnChanging;
  1729. /// <summary>
  1730. /// Occurs after a DataRow has been changed successfully.
  1731. /// </summary>
  1732. [DataCategory ("Data")]
  1733. #if !NET_2_0
  1734. [DataSysDescription ("Occurs after a row in the table has been successfully edited.")]
  1735. #endif
  1736. public event DataRowChangeEventHandler RowChanged;
  1737. /// <summary>
  1738. /// Occurs when a DataRow is changing.
  1739. /// </summary>
  1740. [DataCategory ("Data")]
  1741. #if !NET_2_0
  1742. [DataSysDescription ("Occurs when the row is being changed so that the event handler can modify or cancel the change. The user can modify values in the row and should throw an exception to cancel the edit.")]
  1743. #endif
  1744. public event DataRowChangeEventHandler RowChanging;
  1745. /// <summary>
  1746. /// Occurs after a row in the table has been deleted.
  1747. /// </summary>
  1748. [DataCategory ("Data")]
  1749. #if !NET_2_0
  1750. [DataSysDescription ("Occurs after a row in the table has been successfully deleted.")]
  1751. #endif
  1752. public event DataRowChangeEventHandler RowDeleted;
  1753. /// <summary>
  1754. /// Occurs before a row in the table is about to be deleted.
  1755. /// </summary>
  1756. [DataCategory ("Data")]
  1757. #if !NET_2_0
  1758. [DataSysDescription ("Occurs when a row in the table marked for deletion. Throw an exception to cancel the deletion.")]
  1759. #endif
  1760. public event DataRowChangeEventHandler RowDeleting;
  1761. #if NET_2_0
  1762. /// <summary>
  1763. /// Occurs after the Clear method is called on the datatable.
  1764. /// </summary>
  1765. [DataCategory ("Data")]
  1766. #if !NET_2_0
  1767. [DataSysDescription ("Occurs when the rows in a table is cleared . Throw an exception to cancel the deletion.")]
  1768. #endif
  1769. public event DataTableClearEventHandler TableCleared;
  1770. #endif // NET_2_0
  1771. #endregion // Events
  1772. internal static DataColumn[] ParseSortString (DataTable table, string sort, out ListSortDirection[] sortDirections, bool rejectNoResult)
  1773. {
  1774. DataColumn[] sortColumns = _emptyColumnArray;
  1775. sortDirections = null;
  1776. ArrayList columns = null;
  1777. ArrayList sorts = null;
  1778. if (sort != null && !sort.Equals ("")) {
  1779. columns = new ArrayList ();
  1780. sorts = new ArrayList();
  1781. string[] columnExpression = sort.Trim ().Split (new char[1] {','});
  1782. for (int c = 0; c < columnExpression.Length; c++) {
  1783. string rawColumnName = columnExpression[c].Trim ();
  1784. Match match = SortRegex.Match (rawColumnName);
  1785. CaptureCollection cc = match.Groups["ColName"].Captures ;
  1786. if (cc.Count == 0)
  1787. throw new IndexOutOfRangeException ("Could not find column: " + rawColumnName);
  1788. string columnName = cc[0].Value;
  1789. DataColumn dc = table.Columns[columnName];
  1790. if (dc == null){
  1791. try {
  1792. dc = table.Columns[Int32.Parse (columnName)];
  1793. } catch (FormatException) {
  1794. throw new IndexOutOfRangeException("Cannot find column " + columnName);
  1795. }
  1796. }
  1797. columns.Add (dc);
  1798. cc = match.Groups["Order"].Captures;
  1799. if (cc.Count == 0 || String.Compare (cc[0].Value, "ASC", true) == 0)
  1800. sorts.Add(ListSortDirection.Ascending);
  1801. else
  1802. sorts.Add (ListSortDirection.Descending);
  1803. }
  1804. sortColumns = (DataColumn[]) columns.ToArray (typeof (DataColumn));
  1805. sortDirections = new ListSortDirection[sorts.Count];
  1806. for (int i = 0; i < sortDirections.Length; i++)
  1807. sortDirections[i] = (ListSortDirection)sorts[i];
  1808. }
  1809. if (rejectNoResult) {
  1810. if (sortColumns == null)
  1811. throw new SystemException ("sort expression result is null");
  1812. if (sortColumns.Length == 0)
  1813. throw new SystemException("sort expression result is 0");
  1814. }
  1815. return sortColumns;
  1816. }
  1817. private void UpdatePropertyDescriptorsCache()
  1818. {
  1819. PropertyDescriptor[] descriptors = new PropertyDescriptor[Columns.Count + ChildRelations.Count];
  1820. int index = 0;
  1821. foreach(DataColumn col in Columns) {
  1822. descriptors[index++] = new DataColumnPropertyDescriptor(col);
  1823. }
  1824. foreach(DataRelation rel in ChildRelations) {
  1825. descriptors[index++] = new DataRelationPropertyDescriptor(rel);
  1826. }
  1827. _propertyDescriptorsCache = new PropertyDescriptorCollection(descriptors);
  1828. }
  1829. internal PropertyDescriptorCollection GetPropertyDescriptorCollection()
  1830. {
  1831. if (_propertyDescriptorsCache == null) {
  1832. UpdatePropertyDescriptorsCache();
  1833. }
  1834. return _propertyDescriptorsCache;
  1835. }
  1836. internal void ResetPropertyDescriptorsCache() {
  1837. _propertyDescriptorsCache = null;
  1838. }
  1839. }
  1840. }