2 // System.Data.DataRow.cs
5 // Rodrigo Moya <rodrigo@ximian.com>
6 // Daniel Morgan <danmorg@sc.rr.com>
7 // Tim Coleman <tim@timcoleman.com>
8 // Ville Palo <vi64pa@koti.soon.fi>
9 // Alan Tam Siu Lung <Tam@SiuLung.com>
10 // Sureshkumar T <tsureshkumar@novell.com>
12 // (C) Ximian, Inc 2002
13 // (C) Daniel Morgan 2002, 2003
14 // Copyright (C) 2002 Tim Coleman
18 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
20 // Permission is hereby granted, free of charge, to any person obtaining
21 // a copy of this software and associated documentation files (the
22 // "Software"), to deal in the Software without restriction, including
23 // without limitation the rights to use, copy, modify, merge, publish,
24 // distribute, sublicense, and/or sell copies of the Software, and to
25 // permit persons to whom the Software is furnished to do so, subject to
26 // the following conditions:
28 // The above copyright notice and this permission notice shall be
29 // included in all copies or substantial portions of the Software.
31 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
32 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
33 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
34 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
35 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
36 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
37 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
41 using System.Data.Common;
42 using System.Collections;
43 using System.Globalization;
46 namespace System.Data {
48 /// Represents a row of data in a DataTable.
55 private DataTable _table;
57 internal int _original = -1;
58 internal int _current = -1;
59 internal int _proposed = -1;
61 private ArrayList _columnErrors;
62 private string rowError;
63 private DataRowState rowState;
64 internal int xmlRowID = 0;
65 internal bool _nullConstraintViolation;
66 private string _nullConstraintMessage;
67 private bool editing = false;
68 private bool _hasParentCollection;
69 private bool _inChangingEvent;
72 private XmlDataDocument.XmlDataElement mappedElement;
73 internal bool _inExpressionEvaluation = false;
80 /// This member supports the .NET Framework infrastructure and is not intended to be
81 /// used directly from your code.
83 protected internal DataRow (DataRowBuilder builder)
85 _table = builder.Table;
86 // Get the row id from the builder.
87 _rowId = builder._rowId;
89 _proposed = _table.RecordCache.NewRecord();
90 // Initialise the data columns of the row with the dafault values, if any
91 // TODO : should proposed version be available immediately after record creation ?
92 foreach(DataColumn column in _table.Columns) {
93 column.DataContainer.CopyValue(_table.DefaultValuesRowIndex,_proposed);
96 rowError = String.Empty;
98 //on first creating a DataRow it is always detached.
99 rowState = DataRowState.Detached;
101 ArrayList aiColumns = _table.Columns.AutoIncrmentColumns;
102 foreach (DataColumn dc in aiColumns) {
103 this [dc] = dc.AutoIncrementValue();
106 // create mapped XmlDataElement
107 DataSet ds = _table.DataSet;
108 if (ds != null && ds._xmlDataDocument != null)
109 mappedElement = new XmlDataDocument.XmlDataElement (this, _table.Prefix, _table.TableName, _table.Namespace, ds._xmlDataDocument);
112 internal DataRow(DataTable table,int rowId)
118 #endregion // Constructors
122 private ArrayList ColumnErrors
125 if (_columnErrors == null) {
126 _columnErrors = new ArrayList();
128 return _columnErrors;
132 _columnErrors = value;
137 /// Gets a value indicating whether there are errors in a row.
139 public bool HasErrors {
141 if (RowError != string.Empty)
144 foreach(String columnError in ColumnErrors) {
145 if (columnError != null && columnError != string.Empty) {
154 /// Gets or sets the data stored in the column specified by name.
156 public object this[string columnName] {
157 get { return this[columnName, DataRowVersion.Default]; }
159 int columnIndex = _table.Columns.IndexOf (columnName);
160 if (columnIndex == -1)
161 throw new IndexOutOfRangeException ();
162 this[columnIndex] = value;
167 /// Gets or sets the data stored in specified DataColumn
169 public object this[DataColumn column] {
172 return this[column, DataRowVersion.Default];}
174 int columnIndex = _table.Columns.IndexOf (column);
175 if (columnIndex == -1)
176 throw new ArgumentException ("The column does not belong to this table.");
177 this[columnIndex] = value;
182 /// Gets or sets the data stored in column specified by index.
184 public object this[int columnIndex] {
185 get { return this[columnIndex, DataRowVersion.Default]; }
187 if (columnIndex < 0 || columnIndex > _table.Columns.Count)
188 throw new IndexOutOfRangeException ();
189 if (rowState == DataRowState.Deleted)
190 throw new DeletedRowInaccessibleException ();
192 DataColumn column = _table.Columns[columnIndex];
193 _table.ChangingDataColumn (this, column, value);
195 if (value == null && column.DataType != typeof(string)) {
196 throw new ArgumentException("Cannot set column " + column.ColumnName + " to be null, Please use DBNull instead");
199 CheckValue (value, column);
201 bool orginalEditing = editing;
202 if (!orginalEditing) {
206 column[_proposed] = value;
207 _table.ChangedDataColumn (this, column, value);
208 if (!orginalEditing) {
215 /// Gets the specified version of data stored in the named column.
217 public object this[string columnName, DataRowVersion version] {
219 int columnIndex = _table.Columns.IndexOf (columnName);
220 if (columnIndex == -1)
221 throw new IndexOutOfRangeException ();
222 return this[columnIndex, version];
227 /// Gets the specified version of data stored in the specified DataColumn.
229 public object this[DataColumn column, DataRowVersion version] {
231 if (column.Table != Table)
232 throw new ArgumentException ("The column does not belong to this table.");
233 int columnIndex = column.Ordinal;
234 return this[columnIndex, version];
239 /// Sets the index into the container records for the original version. Apart
240 /// from that, it makes sure it pools the record used earlier if they are not
241 /// used by other versions.
243 internal int Original
245 get { return _original;}
247 if (_original == value)
251 && _current != _original
252 && _proposed != _original)
253 Table.RecordCache.DisposeRecord (_original);
259 /// Sets the index into the container records for the proposed version. Apart
260 /// from that, it makes sure it pools the record used earlier if they are not
261 /// used by other versions.
262 internal int Proposed
264 get { return _proposed;}
266 if (_proposed == value)
269 && _proposed != _current
270 && _proposed != _original)
271 Table.RecordCache.DisposeRecord (_proposed);
277 /// Sets the index into the container records for the current version. Apart
278 /// from that, it makes sure it pools the record used earlier if they are not
279 /// used by other versions.
282 get { return _current;}
284 if (_current == value)
287 && _current != _original
288 && _current != _proposed)
289 Table.RecordCache.DisposeRecord (_current);
295 /// Set a value for the column into the offset specified by the version.<br>
296 /// If the value is auto increment or null, necessary auto increment value
297 /// or the default value will be used.
299 internal void SetValue (int column, object value, int version)
301 DataColumn dc = Table.Columns[column];
303 if (value == null && ! dc.AutoIncrement) // set default value / auto increment
304 value = dc.DefaultValue;
306 Table.ChangingDataColumn (this, dc, value);
307 CheckValue (value, dc);
308 if ( ! dc.AutoIncrement)
309 dc [version] = value;
310 else if (_proposed >= 0 && _proposed != version) // proposed holds the AI
311 dc [version] = dc [_proposed];
315 /// Gets the data stored in the column, specified by index and version of the data to
318 public object this[int columnIndex, DataRowVersion version] {
320 if (columnIndex < 0 || columnIndex > _table.Columns.Count)
321 throw new IndexOutOfRangeException ();
322 // Accessing deleted rows
323 if (!_inExpressionEvaluation && rowState == DataRowState.Deleted && version != DataRowVersion.Original)
324 throw new DeletedRowInaccessibleException ("Deleted row information cannot be accessed through the row.");
326 DataColumn column = _table.Columns[columnIndex];
327 if (column.Expression != String.Empty) {
328 object o = column.CompiledExpression.Eval (this);
329 return Convert.ChangeType (o, column.DataType);
332 if (rowState == DataRowState.Detached && version == DataRowVersion.Default && _proposed < 0)
333 throw new RowNotInTableException("This row has been removed from a table and does not have any data. BeginEdit() will allow creation of new data in this row.");
335 int recordIndex = IndexFromVersion(version);
337 if (recordIndex >= 0) {
338 return column[recordIndex];
341 throw new VersionNotFoundException (Locale.GetText ("There is no " + version.ToString () + " data to access."));
346 /// Gets or sets all of the values for this row through an array.
348 public object[] ItemArray {
351 if (rowState == DataRowState.Detached)
352 throw new RowNotInTableException("This row has been removed from a table and does not have any data. BeginEdit() will allow creation of new data in this row.");
353 // Accessing deleted rows
354 if (rowState == DataRowState.Deleted)
355 throw new DeletedRowInaccessibleException ("Deleted row information cannot be accessed through the row.");
357 object[] items = new object[_table.Columns.Count];
358 foreach(DataColumn column in _table.Columns) {
359 items[column.Ordinal] = column[_current];
364 if (value.Length > _table.Columns.Count)
365 throw new ArgumentException ();
367 if (rowState == DataRowState.Deleted)
368 throw new DeletedRowInaccessibleException ();
370 bool orginalEditing = editing;
371 if (!orginalEditing) {
374 object newVal = null;
375 DataColumnChangeEventArgs e = new DataColumnChangeEventArgs();
376 foreach(DataColumn column in _table.Columns) {
377 int i = column.Ordinal;
378 newVal = (i < value.Length) ? value[i] : null;
380 e.Initialize(this, column, newVal);
381 _table.RaiseOnColumnChanged(e);
382 CheckValue (e.ProposedValue, column);
383 column[_proposed] = e.ProposedValue;
385 if (!orginalEditing) {
391 internal bool IsEditing {
392 get { return editing; }
396 /// Gets the current state of the row in regards to its relationship to the
397 /// DataRowCollection.
399 public DataRowState RowState {
406 /// Gets the DataTable for which this row has a schema.
408 public DataTable Table {
415 /// Gets and sets index of row. This is used from
418 internal int XmlRowID {
428 /// Gets and sets index of row.
439 #endregion // Properties
443 //FIXME?: Couldn't find a way to set the RowState when adding the DataRow
444 //to a Datatable so I added this method. Delete if there is a better way.
445 internal void AttachRow() {
447 Table.RecordCache.DisposeRecord(_current);
449 _current = _proposed;
451 rowState = DataRowState.Added;
454 //FIXME?: Couldn't find a way to set the RowState when removing the DataRow
455 //from a Datatable so I added this method. Delete if there is a better way.
456 internal void DetachRow() {
457 if (_proposed >= 0) {
458 _table.RecordCache.DisposeRecord(_proposed);
462 _hasParentCollection = false;
463 rowState = DataRowState.Detached;
466 private void CheckValue (object v, DataColumn col)
468 if (_hasParentCollection && col.ReadOnly) {
469 throw new ReadOnlyException ();
472 if (v == null || v == DBNull.Value) {
473 if (col.AllowDBNull || col.AutoIncrement || col.DefaultValue != DBNull.Value) {
477 //Constraint violations during data load is raise in DataTable EndLoad
478 this._nullConstraintViolation = true;
479 if (this.Table._duringDataLoad) {
480 this.Table._nullConstraintViolationDuringDataLoad = true;
482 _nullConstraintMessage = "Column '" + col.ColumnName + "' does not allow nulls.";
487 internal void SetValuesFromDataRecord(IDataRecord record, int[] mapping)
489 // bool orginalEditing = editing;
490 // if (!orginalEditing) {
494 if (!HasVersion(DataRowVersion.Proposed)) {
495 _proposed = Table.RecordCache.NewRecord();
499 for(int i=0; i < Table.Columns.Count; i++) {
500 DataColumn column = Table.Columns[i];
501 if (mapping [i] < 0) { // no mapping
502 if (! column.AutoIncrement)
503 column.DataContainer [_proposed] = column.DefaultValue;
507 column.DataContainer.SetItemFromDataRecord(_proposed, record,mapping[i]);
508 if ( column.AutoIncrement ) {
509 column.UpdateAutoIncrementValue(column.DataContainer.GetInt64(_proposed));
514 Table.RecordCache.DisposeRecord(_proposed);
519 // if (!orginalEditing) {
525 /// Gets or sets the custom error description for a row.
527 public string RowError {
536 internal int IndexFromVersion(DataRowVersion version)
538 if (HasVersion(version))
542 case DataRowVersion.Default:
543 if (editing || rowState == DataRowState.Detached) {
544 recordIndex = _proposed;
547 recordIndex = _current;
550 case DataRowVersion.Proposed:
551 recordIndex = _proposed;
553 case DataRowVersion.Current:
554 recordIndex = _current;
556 case DataRowVersion.Original:
557 recordIndex = _original;
560 throw new ArgumentException ();
567 internal XmlDataDocument.XmlDataElement DataElement {
568 get { return mappedElement; }
569 set { mappedElement = value; }
572 internal void SetOriginalValue (string columnName, object val)
574 DataColumn column = _table.Columns[columnName];
575 _table.ChangingDataColumn (this, column, val);
577 if (_original < 0 || _original == _current) {
578 // This really creates a new record version if one does not exist
579 _original = Table.RecordCache.NewRecord();
581 CheckValue (val, column);
582 column[_original] = val;
583 rowState = DataRowState.Modified;
587 /// Commits all the changes made to this row since the last time AcceptChanges was
590 public void AcceptChanges ()
592 EndEdit(); // in case it hasn't been called
594 case DataRowState.Unchanged:
596 case DataRowState.Added:
597 case DataRowState.Modified:
598 rowState = DataRowState.Unchanged;
600 case DataRowState.Deleted:
601 _table.Rows.RemoveInternal (this);
604 case DataRowState.Detached:
605 throw new RowNotInTableException("Cannot perform this operation on a row not in the table.");
607 // Accept from detached
608 if (_original != _current)
613 /// Begins an edit operation on a DataRow object.
615 public void BeginEdit ()
617 if (_inChangingEvent)
618 throw new InRowChangingEventException("Cannot call BeginEdit inside an OnRowChanging event.");
619 if (rowState == DataRowState.Deleted)
620 throw new DeletedRowInaccessibleException ();
621 if (!HasVersion (DataRowVersion.Proposed)) {
622 _proposed = Table.RecordCache.NewRecord();
623 foreach(DataColumn column in Table.Columns) {
624 column.DataContainer.CopyValue(_current,_proposed);
627 // setting editing to true stops validations on the row
632 /// Cancels the current edit on the row.
634 public void CancelEdit ()
636 if (_inChangingEvent)
637 throw new InRowChangingEventException("Cannot call CancelEdit inside an OnRowChanging event.");
639 if (HasVersion (DataRowVersion.Proposed)) {
640 Table.RecordCache.DisposeRecord(_proposed);
642 if (rowState == DataRowState.Modified) {
643 rowState = DataRowState.Unchanged;
649 /// Clears the errors for the row, including the RowError and errors set with
652 public void ClearErrors ()
654 rowError = String.Empty;
655 ColumnErrors.Clear();
659 /// Deletes the DataRow.
661 public void Delete ()
663 _table.DeletingDataRow(this, DataRowAction.Delete);
665 case DataRowState.Added:
666 // check what to do with child rows
667 CheckChildRows(DataRowAction.Delete);
668 _table.DeleteRowFromIndexes (this);
669 Table.Rows.RemoveInternal (this);
671 // if row was in Added state we move it to Detached.
674 case DataRowState.Deleted:
677 // check what to do with child rows
678 CheckChildRows(DataRowAction.Delete);
679 _table.DeleteRowFromIndexes (this);
680 rowState = DataRowState.Deleted;
683 _table.DeletedDataRow(this, DataRowAction.Delete);
686 // check the child rows of this row before deleting the row.
687 private void CheckChildRows(DataRowAction action)
690 // in this method we find the row that this row is in a relation with them.
691 // in shortly we find all child rows of this row.
692 // then we function according to the DeleteRule of the foriegnkey.
695 // 1. find if this row is attached to dataset.
696 // 2. find if EnforceConstraints is true.
697 // 3. find if there are any constraint on the table that the row is in.
698 if (_table.DataSet != null && _table.DataSet.EnforceConstraints && _table.Constraints.Count > 0)
700 foreach (DataTable table in _table.DataSet.Tables)
702 // loop on all ForeignKeyConstrain of the table.
703 foreach (ForeignKeyConstraint fk in table.Constraints.ForeignKeyConstraints)
705 if (fk.RelatedTable == _table)
708 if (action == DataRowAction.Delete)
709 rule = fk.DeleteRule;
711 rule = fk.UpdateRule;
712 CheckChildRows(fk, action, rule);
719 private void CheckChildRows(ForeignKeyConstraint fkc, DataRowAction action, Rule rule)
721 DataRow[] childRows = GetChildRows(fkc, DataRowVersion.Default);
724 case Rule.Cascade: // delete or change all relted rows.
725 if (childRows != null)
727 for (int j = 0; j < childRows.Length; j++)
729 // if action is delete we delete all child rows
730 if (action == DataRowAction.Delete)
732 if (childRows[j].RowState != DataRowState.Deleted)
733 childRows[j].Delete();
735 // if action is change we change the values in the child row
736 else if (action == DataRowAction.Change)
738 // change only the values in the key columns
739 // set the childcolumn value to the new parent row value
740 for (int k = 0; k < fkc.Columns.Length; k++)
741 childRows[j][fkc.Columns[k]] = this[fkc.RelatedColumns[k], DataRowVersion.Proposed];
746 case Rule.None: // throw an exception if there are any child rows.
747 if (childRows != null)
749 for (int j = 0; j < childRows.Length; j++)
751 if (childRows[j].RowState != DataRowState.Deleted)
753 string changeStr = "Cannot change this row because constraints are enforced on relation " + fkc.ConstraintName +", and changing this row will strand child rows.";
754 string delStr = "Cannot delete this row because constraints are enforced on relation " + fkc.ConstraintName +", and deleting this row will strand child rows.";
755 string message = action == DataRowAction.Delete ? delStr : changeStr;
756 throw new InvalidConstraintException(message);
761 case Rule.SetDefault: // set the values in the child rows to the defult value of the columns.
762 if (childRows != null && childRows.Length > 0) {
763 int defaultValuesRowIndex = childRows[0].Table.DefaultValuesRowIndex;
764 foreach(DataRow childRow in childRows) {
765 if (childRow.RowState != DataRowState.Deleted) {
766 int defaultIdx = childRow.IndexFromVersion(DataRowVersion.Default);
767 foreach(DataColumn column in fkc.Columns) {
768 column.DataContainer.CopyValue(defaultValuesRowIndex,defaultIdx);
774 case Rule.SetNull: // set the values in the child row to null.
775 if (childRows != null)
777 for (int j = 0; j < childRows.Length; j++)
779 DataRow child = childRows[j];
780 if (childRows[j].RowState != DataRowState.Deleted)
782 // set only the key columns to DBNull
783 for (int k = 0; k < fkc.Columns.Length; k++)
784 child.SetNull(fkc.Columns[k]);
794 /// Ends the edit occurring on the row.
796 public void EndEdit ()
798 if (_inChangingEvent)
799 throw new InRowChangingEventException("Cannot call EndEdit inside an OnRowChanging event.");
800 if (rowState == DataRowState.Detached)
806 CheckReadOnlyStatus();
807 if (HasVersion (DataRowVersion.Proposed))
809 _inChangingEvent = true;
812 _table.ChangingDataRow(this, DataRowAction.Change);
816 _inChangingEvent = false;
818 if (rowState == DataRowState.Unchanged)
819 rowState = DataRowState.Modified;
821 //Calling next method validates UniqueConstraints
825 if ((_table.DataSet == null || _table.DataSet.EnforceConstraints) && !_table._duringDataLoad)
826 _table.Rows.ValidateDataRowInternal(this);
831 Table.RecordCache.DisposeRecord(_proposed);
836 // Now we are going to check all child rows of current row.
837 // In the case the cascade is true the child rows will look up for
838 // parent row. since lookup in index is always on current,
839 // we have to move proposed version of current row to current
840 // in the case of check child row failure we are rolling
841 // current row state back.
842 int backup = _current;
843 _current = _proposed;
844 bool editing_backup = editing;
847 // check all child rows.
848 CheckChildRows(DataRowAction.Change);
850 if (_original != backup) {
851 Table.RecordCache.DisposeRecord(backup);
854 catch (Exception ex) {
855 // if check child rows failed - rollback to previous state
856 // i.e. restore proposed and current versions
857 _proposed = _current;
859 editing = editing_backup;
860 // since we failed - propagate an exception
863 _table.ChangedDataRow(this, DataRowAction.Change);
868 /// Gets the child rows of this DataRow using the specified DataRelation.
870 public DataRow[] GetChildRows (DataRelation relation)
872 return GetChildRows (relation, DataRowVersion.Default);
876 /// Gets the child rows of a DataRow using the specified RelationName of a
879 public DataRow[] GetChildRows (string relationName)
881 return GetChildRows (Table.DataSet.Relations[relationName]);
885 /// Gets the child rows of a DataRow using the specified DataRelation, and
888 public DataRow[] GetChildRows (DataRelation relation, DataRowVersion version)
890 if (relation == null)
891 return new DataRow[0];
893 //if (this.Table == null || RowState == DataRowState.Detached)
894 if (this.Table == null)
895 throw new RowNotInTableException("This row has been removed from a table and does not have any data. BeginEdit() will allow creation of new data in this row.");
897 if (relation.DataSet != this.Table.DataSet)
898 throw new ArgumentException();
900 if (_table != relation.ParentTable)
901 throw new InvalidConstraintException ("GetChildRow requires a row whose Table is " + relation.ParentTable + ", but the specified row's table is " + _table);
903 if (relation.ChildKeyConstraint != null)
904 return GetChildRows (relation.ChildKeyConstraint, version);
906 ArrayList rows = new ArrayList();
907 DataColumn[] parentColumns = relation.ParentColumns;
908 DataColumn[] childColumns = relation.ChildColumns;
909 int numColumn = parentColumns.Length;
910 if (HasVersion(version))
912 object[] vals = new object[parentColumns.Length];
913 for (int i = 0; i < vals.Length; i++)
914 vals[i] = this[parentColumns[i], version];
916 foreach (DataRow row in relation.ChildTable.Rows)
918 bool allColumnsMatch = false;
919 if (row.HasVersion(DataRowVersion.Default))
921 allColumnsMatch = true;
922 for (int columnCnt = 0; columnCnt < numColumn; ++columnCnt)
924 if (!vals[columnCnt].Equals(
925 row[childColumns[columnCnt], DataRowVersion.Default]))
927 allColumnsMatch = false;
932 if (allColumnsMatch) rows.Add(row);
935 throw new VersionNotFoundException("There is no " + version + " data to accces.");
937 DataRow[] result = relation.ChildTable.NewRowArray(rows.Count);
938 rows.CopyTo(result, 0);
943 /// Gets the child rows of a DataRow using the specified RelationName of a
944 /// DataRelation, and DataRowVersion.
946 public DataRow[] GetChildRows (string relationName, DataRowVersion version)
948 return GetChildRows (Table.DataSet.Relations[relationName], version);
951 private DataRow[] GetChildRows (ForeignKeyConstraint fkc, DataRowVersion version)
953 ArrayList rows = new ArrayList();
954 DataColumn[] parentColumns = fkc.RelatedColumns;
955 DataColumn[] childColumns = fkc.Columns;
956 int numColumn = parentColumns.Length;
957 if (HasVersion(version)) {
958 Index index = fkc.Index;
960 // get the child rows from the index
961 Node[] childNodes = index.FindAllSimple (parentColumns, IndexFromVersion(version));
962 for (int i = 0; i < childNodes.Length; i++) {
963 rows.Add (childNodes[i].Row);
966 else { // if there is no index we search manualy.
967 int curIndex = IndexFromVersion(DataRowVersion.Default);
968 int tmpRecord = fkc.Table.RecordCache.NewRecord();
971 for (int i = 0; i < numColumn; i++) {
972 // according to MSDN: the DataType value for both columns must be identical.
973 childColumns[i].DataContainer.CopyValue(parentColumns[i].DataContainer, curIndex, tmpRecord);
976 foreach (DataRow row in fkc.Table.Rows) {
977 bool allColumnsMatch = false;
978 if (row.HasVersion(DataRowVersion.Default)) {
979 allColumnsMatch = true;
980 int childIndex = row.IndexFromVersion(DataRowVersion.Default);
981 for (int columnCnt = 0; columnCnt < numColumn; ++columnCnt) {
982 if (childColumns[columnCnt].DataContainer.CompareValues(childIndex, tmpRecord) != 0) {
983 allColumnsMatch = false;
988 if (allColumnsMatch) {
994 fkc.Table.RecordCache.DisposeRecord(tmpRecord);
998 throw new VersionNotFoundException("There is no " + version + " data to accces.");
1000 DataRow[] result = fkc.Table.NewRowArray(rows.Count);
1001 rows.CopyTo(result, 0);
1006 /// Gets the error description of the specified DataColumn.
1008 public string GetColumnError (DataColumn column)
1010 return GetColumnError (_table.Columns.IndexOf(column));
1014 /// Gets the error description for the column specified by index.
1016 public string GetColumnError (int columnIndex)
1018 if (columnIndex < 0 || columnIndex >= Table.Columns.Count)
1019 throw new IndexOutOfRangeException ();
1021 string retVal = null;
1022 if (columnIndex < ColumnErrors.Count) {
1023 retVal = (String) ColumnErrors[columnIndex];
1025 return (retVal != null) ? retVal : String.Empty;
1029 /// Gets the error description for the column, specified by name.
1031 public string GetColumnError (string columnName)
1033 return GetColumnError (_table.Columns.IndexOf(columnName));
1037 /// Gets an array of columns that have errors.
1039 public DataColumn[] GetColumnsInError ()
1041 ArrayList dataColumns = new ArrayList ();
1043 int columnOrdinal = 0;
1044 foreach(String columnError in ColumnErrors) {
1045 if (columnError != null && columnError != String.Empty) {
1046 dataColumns.Add (_table.Columns[columnOrdinal]);
1051 return (DataColumn[])(dataColumns.ToArray (typeof(DataColumn)));
1055 /// Gets the parent row of a DataRow using the specified DataRelation.
1057 public DataRow GetParentRow (DataRelation relation)
1059 return GetParentRow (relation, DataRowVersion.Default);
1063 /// Gets the parent row of a DataRow using the specified RelationName of a
1066 public DataRow GetParentRow (string relationName)
1068 return GetParentRow (relationName, DataRowVersion.Default);
1072 /// Gets the parent row of a DataRow using the specified DataRelation, and
1075 public DataRow GetParentRow (DataRelation relation, DataRowVersion version)
1077 DataRow[] rows = GetParentRows(relation, version);
1078 if (rows.Length == 0) return null;
1083 /// Gets the parent row of a DataRow using the specified RelationName of a
1084 /// DataRelation, and DataRowVersion.
1086 public DataRow GetParentRow (string relationName, DataRowVersion version)
1088 return GetParentRow (Table.DataSet.Relations[relationName], version);
1092 /// Gets the parent rows of a DataRow using the specified DataRelation.
1094 public DataRow[] GetParentRows (DataRelation relation)
1096 return GetParentRows (relation, DataRowVersion.Default);
1100 /// Gets the parent rows of a DataRow using the specified RelationName of a
1103 public DataRow[] GetParentRows (string relationName)
1105 return GetParentRows (relationName, DataRowVersion.Default);
1109 /// Gets the parent rows of a DataRow using the specified DataRelation, and
1112 public DataRow[] GetParentRows (DataRelation relation, DataRowVersion version)
1114 // TODO: Caching for better preformance
1115 if (relation == null)
1116 return new DataRow[0];
1118 if (this.Table == null)
1119 throw new RowNotInTableException("This row has been removed from a table and does not have any data. BeginEdit() will allow creation of new data in this row.");
1121 if (relation.DataSet != this.Table.DataSet)
1122 throw new ArgumentException();
1124 if (_table != relation.ChildTable)
1125 throw new InvalidConstraintException ("GetParentRows requires a row whose Table is " + relation.ChildTable + ", but the specified row's table is " + _table);
1127 ArrayList rows = new ArrayList();
1128 DataColumn[] parentColumns = relation.ParentColumns;
1129 DataColumn[] childColumns = relation.ChildColumns;
1130 int numColumn = parentColumns.Length;
1131 if (HasVersion(version)) {
1132 Index indx = relation.ParentTable.GetIndexByColumns (parentColumns);
1134 (Table == null || Table.DataSet == null ||
1135 Table.DataSet.EnforceConstraints)) { // get the child rows from the index
1136 Node[] childNodes = indx.FindAllSimple(childColumns, IndexFromVersion(version));
1137 for (int i = 0; i < childNodes.Length; i++) {
1138 rows.Add (childNodes[i].Row);
1141 else { // no index so we have to search manualy.
1142 int curIndex = IndexFromVersion(DataRowVersion.Default);
1143 int tmpRecord = relation.ParentTable.RecordCache.NewRecord();
1145 for (int i = 0; i < numColumn; i++) {
1146 // according to MSDN: the DataType value for both columns must be identical.
1147 parentColumns[i].DataContainer.CopyValue(childColumns[i].DataContainer, curIndex, tmpRecord);
1150 foreach (DataRow row in relation.ParentTable.Rows) {
1151 bool allColumnsMatch = false;
1152 if (row.HasVersion(DataRowVersion.Default)) {
1153 allColumnsMatch = true;
1154 int parentIndex = row.IndexFromVersion(DataRowVersion.Default);
1155 for (int columnCnt = 0; columnCnt < numColumn; columnCnt++) {
1156 if (parentColumns[columnCnt].DataContainer.CompareValues(parentIndex, tmpRecord) != 0) {
1157 allColumnsMatch = false;
1162 if (allColumnsMatch) {
1168 relation.ParentTable.RecordCache.DisposeRecord(tmpRecord);
1172 throw new VersionNotFoundException("There is no " + version + " data to accces.");
1174 DataRow[] result = relation.ParentTable.NewRowArray(rows.Count);
1175 rows.CopyTo(result, 0);
1180 /// Gets the parent rows of a DataRow using the specified RelationName of a
1181 /// DataRelation, and DataRowVersion.
1183 public DataRow[] GetParentRows (string relationName, DataRowVersion version)
1185 return GetParentRows (Table.DataSet.Relations[relationName], version);
1189 /// Gets a value indicating whether a specified version exists.
1191 public bool HasVersion (DataRowVersion version)
1194 case DataRowVersion.Default:
1195 if (rowState == DataRowState.Deleted && !_inExpressionEvaluation)
1197 if (rowState == DataRowState.Detached)
1198 return _proposed >= 0;
1200 case DataRowVersion.Proposed:
1201 if (rowState == DataRowState.Deleted && !_inExpressionEvaluation)
1203 return _proposed >= 0;
1204 case DataRowVersion.Current:
1205 if ((rowState == DataRowState.Deleted && !_inExpressionEvaluation) || rowState == DataRowState.Detached)
1207 return _current >= 0;
1208 case DataRowVersion.Original:
1209 if (rowState == DataRowState.Detached)
1211 return _original >= 0;
1217 /// Gets a value indicating whether the specified DataColumn contains a null value.
1219 public bool IsNull (DataColumn column)
1221 return IsNull(column, DataRowVersion.Default);
1225 /// Gets a value indicating whether the column at the specified index contains a null
1228 public bool IsNull (int columnIndex)
1230 return IsNull(Table.Columns[columnIndex]);
1234 /// Gets a value indicating whether the named column contains a null value.
1236 public bool IsNull (string columnName)
1238 return IsNull(Table.Columns[columnName]);
1242 /// Gets a value indicating whether the specified DataColumn and DataRowVersion
1243 /// contains a null value.
1245 public bool IsNull (DataColumn column, DataRowVersion version)
1247 return column.DataContainer.IsNull(IndexFromVersion(version));
1251 /// Returns a value indicating whether all of the row columns specified contain a null value.
1253 internal bool IsNullColumns(DataColumn[] columns)
1255 bool allNull = true;
1256 for (int i = 0; i < columns.Length; i++)
1258 if (!IsNull(columns[i]))
1268 /// Rejects all changes made to the row since AcceptChanges was last called.
1270 public void RejectChanges ()
1272 if (RowState == DataRowState.Detached)
1273 throw new RowNotInTableException("This row has been removed from a table and does not have any data. BeginEdit() will allow creation of new data in this row.");
1274 // If original is null, then nothing has happened since AcceptChanges
1275 // was last called. We have no "original" to go back to.
1276 if (HasVersion(DataRowVersion.Original)) {
1277 if (_current >= 0 ) {
1278 Table.RecordCache.DisposeRecord(_current);
1280 _current = _original;
1282 _table.ChangedDataRow (this, DataRowAction.Rollback);
1286 case DataRowState.Added:
1287 _table.DeleteRowFromIndexes (this);
1288 _table.Rows.RemoveInternal (this);
1290 case DataRowState.Modified:
1291 if ((_table.DataSet == null || _table.DataSet.EnforceConstraints) && !_table._duringDataLoad)
1292 _table.Rows.ValidateDataRowInternal(this);
1293 rowState = DataRowState.Unchanged;
1295 case DataRowState.Deleted:
1296 rowState = DataRowState.Unchanged;
1297 if ((_table.DataSet == null || _table.DataSet.EnforceConstraints) && !_table._duringDataLoad)
1298 _table.Rows.ValidateDataRowInternal(this);
1304 // If rows are just loaded via Xml the original values are null.
1305 // So in this case we have to remove all columns.
1306 // FIXME: I'm not realy sure, does this break something else, but
1309 if ((rowState & DataRowState.Added) > 0)
1311 _table.DeleteRowFromIndexes (this);
1312 _table.Rows.RemoveInternal (this);
1313 // if row was in Added state we move it to Detached.
1320 /// Sets the error description for a column specified as a DataColumn.
1322 public void SetColumnError (DataColumn column, string error)
1324 SetColumnError (_table.Columns.IndexOf (column), error);
1328 /// Sets the error description for a column specified by index.
1330 public void SetColumnError (int columnIndex, string error)
1332 if (columnIndex < 0 || columnIndex >= Table.Columns.Count)
1333 throw new IndexOutOfRangeException ();
1335 while(ColumnErrors.Count < columnIndex) {
1336 ColumnErrors.Add(null);
1338 ColumnErrors.Add(error);
1342 /// Sets the error description for a column specified by name.
1344 public void SetColumnError (string columnName, string error)
1346 SetColumnError (_table.Columns.IndexOf (columnName), error);
1350 /// Sets the value of the specified DataColumn to a null value.
1352 protected void SetNull (DataColumn column)
1354 this[column] = DBNull.Value;
1358 /// Sets the parent row of a DataRow with specified new parent DataRow.
1360 public void SetParentRow (DataRow parentRow)
1362 SetParentRow(parentRow, null);
1366 /// Sets the parent row of a DataRow with specified new parent DataRow and
1369 public void SetParentRow (DataRow parentRow, DataRelation relation)
1371 if (_table == null || parentRow.Table == null)
1372 throw new RowNotInTableException("This row has been removed from a table and does not have any data. BeginEdit() will allow creation of new data in this row.");
1374 if (parentRow != null && _table.DataSet != parentRow.Table.DataSet)
1375 throw new ArgumentException();
1378 if (relation == null)
1380 foreach (DataRelation parentRel in _table.ParentRelations)
1382 DataColumn[] childCols = parentRel.ChildColumns;
1383 DataColumn[] parentCols = parentRel.ParentColumns;
1385 for (int i = 0; i < parentCols.Length; i++)
1387 if (parentRow == null)
1388 this[childCols[i].Ordinal] = DBNull.Value;
1390 this[childCols[i].Ordinal] = parentRow[parentCols[i]];
1397 DataColumn[] childCols = relation.ChildColumns;
1398 DataColumn[] parentCols = relation.ParentColumns;
1400 for (int i = 0; i < parentCols.Length; i++)
1402 if (parentRow == null)
1403 this[childCols[i].Ordinal] = DBNull.Value;
1405 this[childCols[i].Ordinal] = parentRow[parentCols[i]];
1411 //Copy all values of this DataaRow to the row parameter.
1412 internal void CopyValuesToRow(DataRow row)
1415 throw new ArgumentNullException("row");
1417 throw new ArgumentException("'row' is the same as this object");
1419 foreach(DataColumn column in Table.Columns) {
1420 DataColumn targetColumn = row.Table.Columns[column.ColumnName];
1421 //if a column with the same name exists in both rows copy the values
1422 if(targetColumn != null) {
1423 int index = targetColumn.Ordinal;
1424 if (HasVersion(DataRowVersion.Original)) {
1425 if (row._original < 0) {
1426 row._original = row.Table.RecordCache.NewRecord();
1428 object val = column[_original];
1429 row.CheckValue(val, targetColumn);
1430 targetColumn[row._original] = val;
1432 if (HasVersion(DataRowVersion.Current)) {
1433 if (row._current < 0) {
1434 row._current = row.Table.RecordCache.NewRecord();
1436 object val = column[_current];
1437 row.CheckValue(val, targetColumn);
1438 targetColumn[row._current] = val;
1440 if (HasVersion(DataRowVersion.Proposed)) {
1441 if (row._proposed < 0) {
1442 row._proposed = row.Table.RecordCache.NewRecord();
1444 object val = column[row._proposed];
1445 row.CheckValue(val, targetColumn);
1446 targetColumn[row._proposed] = val;
1449 //Saving the current value as the column value
1450 object defaultVal = column [IndexFromVersion (DataRowVersion.Default)];
1451 row [index] = defaultVal;
1457 // Copy row state - rowState and errors
1458 internal void CopyState(DataRow row)
1460 row.rowState = RowState;
1461 row.RowError = RowError;
1462 row.ColumnErrors = (ArrayList)ColumnErrors.Clone();
1465 internal bool IsRowChanged(DataRowState rowState) {
1466 if((RowState & rowState) != 0)
1469 //we need to find if child rows of this row changed.
1470 //if yes - we should return true
1472 // if the rowState is deleted we should get the original version of the row
1473 // else - we should get the current version of the row.
1474 DataRowVersion version = (rowState == DataRowState.Deleted) ? DataRowVersion.Original : DataRowVersion.Current;
1475 int count = Table.ChildRelations.Count;
1476 for (int i = 0; i < count; i++){
1477 DataRelation rel = Table.ChildRelations[i];
1478 DataRow[] childRows = GetChildRows(rel, version);
1479 for (int j = 0; j < childRows.Length; j++){
1480 if (childRows[j].IsRowChanged(rowState))
1488 internal bool HasParentCollection
1492 return _hasParentCollection;
1496 _hasParentCollection = value;
1500 internal void CheckNullConstraints()
1502 if (_nullConstraintViolation) {
1503 if (HasVersion(DataRowVersion.Proposed)) {
1504 foreach(DataColumn column in Table.Columns) {
1505 if (IsNull(column) && !column.AllowDBNull) {
1506 throw new NoNullAllowedException(_nullConstraintMessage);
1510 _nullConstraintViolation = false;
1514 internal void CheckReadOnlyStatus()
1516 if (HasVersion(DataRowVersion.Proposed)) {
1517 int defaultIdx = IndexFromVersion(DataRowVersion.Default);
1518 foreach(DataColumn column in Table.Columns) {
1519 if ((column.DataContainer.CompareValues(defaultIdx,_proposed) != 0) && column.ReadOnly) {
1520 throw new ReadOnlyException();
1526 #endregion // Methods
1530 /// This method loads a given value into the existing row affecting versions,
1531 /// state based on the LoadOption. The matrix of changes for this method are as
1532 /// mentioned in the DataTable.Load (IDataReader, LoadOption) method.
1534 [MonoTODO ("Raise necessary Events")]
1535 internal void Load (object [] values, LoadOption loadOption, bool is_new)
1537 DataRowAction action = DataRowAction.Change;
1539 int temp = Table.RecordCache.NewRecord ();
1540 for (int i = 0 ; i < Table.Columns.Count; i++)
1541 SetValue (i, values [i], temp);
1543 if (is_new) { // new row
1544 if (editing || RowState == DataRowState.Detached)
1551 if (loadOption == LoadOption.OverwriteChanges
1552 || (loadOption == LoadOption.PreserveChanges
1553 && rowState == DataRowState.Unchanged)) {
1559 rowState = DataRowState.Unchanged;
1560 action = DataRowAction.ChangeCurrentAndOriginal;
1564 if (loadOption == LoadOption.PreserveChanges) {
1565 if (rowState != DataRowState.Deleted) {
1567 rowState = DataRowState.Modified;
1568 action = DataRowAction.ChangeOriginal;
1573 bool not_used = true;
1575 if (rowState != DataRowState.Deleted) {
1576 int index = editing ? _proposed : _current;
1577 if (! RecordCache.CompareRecords (Table, index, temp)) {
1583 if (rowState == DataRowState.Unchanged)
1584 rowState = DataRowState.Modified;
1589 Table.RecordCache.DisposeRecord (temp);