2 // System.Data.DataColumn.cs
5 // Franklin Wise (gracenote@earthlink.net)
6 // Christopher Podurgiel (cpodurgiel@msn.com)
7 // Rodrigo Moya (rodrigo@ximian.com)
8 // Daniel Morgan (danmorg@sc.rr.com)
9 // Tim Coleman (tim@timcoleman.com)
11 // (C) Copyright 2002, Franklin Wise
12 // (C) Chris Podurgiel
13 // (C) Ximian, Inc 2002
14 // Copyright (C) Tim Coleman, 2002
15 // Copyright (C) Daniel Morgan, 2002, 2003
19 using System.ComponentModel;
20 using System.Reflection;
21 using System.Collections;
22 using System.Data.Common;
24 namespace System.Data {
25 internal delegate void DelegateColumnValueChange(DataColumn column, DataRow row, object proposedValue);
28 /// Summary description for DataColumn.
33 [DefaultMember ("Item")]
34 [DefaultProperty ("ColumnName")]
35 [DesignTimeVisible (false)]
36 [TypeConverterAttribute (typeof (ComponentConverter))]
37 public class DataColumn : MarshalByValueComponent
41 //used for constraint validation
42 //if an exception is fired during this event the change should be canceled
43 internal event DelegateColumnValueChange ValidateColumnValueChange;
45 //used for FK Constraint Cascading rules
46 internal event DelegateColumnValueChange ColumnValueChanging;
51 private bool _allowDBNull = true;
52 private bool _autoIncrement;
53 private long _autoIncrementSeed;
54 private long _autoIncrementStep = 1;
55 private long _nextAutoIncrementValue;
56 private bool dataHasBeenSet;
57 private string _caption;
58 private MappingType _columnMapping;
59 private string _columnName;
60 private Type _dataType;
61 private object _defaultValue = DBNull.Value;
62 private string expression;
63 private PropertyCollection _extendedProperties = new PropertyCollection ();
64 private int maxLength = -1; //-1 represents no length limit
65 private string nameSpace = "";
66 private int _ordinal = -1; //-1 represents not part of a collection
67 private string prefix = "";
68 private bool readOnly;
69 private DataTable _table;
76 public DataColumn() : this("", typeof (string), "", MappingType.Element)
80 //TODO: Ctor init vars directly
81 public DataColumn(string columnName): this(columnName, typeof (string), "", MappingType.Element)
85 public DataColumn(string columnName, Type dataType): this(columnName, dataType, "", MappingType.Element)
89 public DataColumn( string columnName, Type dataType,
90 string expr): this(columnName, dataType, expr, MappingType.Element)
94 public DataColumn(string columnName, Type dataType,
95 string expr, MappingType type)
97 ColumnName = (columnName == null ? "" : columnName);
99 if(dataType == null) {
100 throw new ArgumentNullException("dataType can't be null.");
104 Expression = expr == null ? "" : expr;
105 ColumnMapping = type;
111 [DataCategory ("Data")]
112 [DataSysDescription ("Indicates whether null values are allowed in this column.")]
113 [DefaultValue (true)]
114 public bool AllowDBNull
120 //TODO: If we are a part of the table and this value changes
121 //we need to validate that all the existing values conform to the new setting
129 //if Value == false case
132 if (_table.Rows.Count > 0)
134 bool nullsFound = false;
135 for(int r = 0; r < _table.Rows.Count; r++) {
136 DataRow row = _table.Rows[r];
137 if(row.IsNull(this)) {
144 throw new DataException("Column '" + ColumnName + "' has null values in it.");
145 //TODO: Validate no null values exist
146 //do we also check different versions of the row??
150 _allowDBNull = value;
155 /// Gets or sets a value indicating whether the column automatically increments the value of the column for new rows added to the table.
158 /// If the type of this column is not Int16, Int32, or Int64 when this property is set,
159 /// the DataType property is coerced to Int32. An exception is generated if this is a computed column
160 /// (that is, the Expression property is set.) The incremented value is used only if the row's value for this column,
161 /// when added to the columns collection, is equal to the default value.
163 [DataCategory ("Data")]
164 [DataSysDescription ("Indicates whether the column automatically increments itself for new rows added to the table. The type of this column must be Int16, Int32, or Int64.")]
165 [DefaultValue (false)]
166 [RefreshProperties (RefreshProperties.All)]
167 public bool AutoIncrement
170 return _autoIncrement;
175 //Can't be true if this is a computed column
176 if (Expression != string.Empty)
178 throw new ArgumentException("Can not Auto Increment a computed column.");
181 //If the DataType of this Column isn't an Int
183 TypeCode typeCode = Type.GetTypeCode(_dataType);
184 if(typeCode != TypeCode.Int16 &&
185 typeCode != TypeCode.Int32 &&
186 typeCode != TypeCode.Int64)
188 _dataType = typeof(Int32);
191 _autoIncrement = value;
195 [DataCategory ("Data")]
196 [DataSysDescription ("Indicates the starting value for an AutoIncrement column.")]
198 public long AutoIncrementSeed
201 return _autoIncrementSeed;
204 _autoIncrementSeed = value;
205 _nextAutoIncrementValue = _autoIncrementSeed;
209 [DataCategory ("Data")]
210 [DataSysDescription ("Indicates the increment used by an AutoIncrement column.")]
212 public long AutoIncrementStep
215 return _autoIncrementStep;
218 _autoIncrementStep = value;
222 internal void UpdateAutoIncrementValue (long value)
224 if(value > _nextAutoIncrementValue) {
225 _nextAutoIncrementValue = value;
226 AutoIncrementValue ();
230 internal long AutoIncrementValue ()
232 long currentValue = _nextAutoIncrementValue;
233 _nextAutoIncrementValue += AutoIncrementStep;
237 internal long GetAutoIncrementValue ()
239 return _nextAutoIncrementValue;
242 internal bool DataHasBeenSet {
244 return dataHasBeenSet;
247 dataHasBeenSet = value;
251 [DataCategory ("Data")]
252 [DataSysDescription ("Indicates the default user-interface caption for this column.")]
253 public string Caption
265 [DataSysDescription ("Indicates how this column persists in XML: as an attribute, element, simple content node, or nothing.")]
266 [DefaultValue (MappingType.Element)]
267 public virtual MappingType ColumnMapping
270 return _columnMapping;
273 _columnMapping = value;
277 [DataCategory ("Data")]
278 [DataSysDescription ("Indicates the name used to look up this column in the Columns collection of a DataTable.")]
279 [RefreshProperties (RefreshProperties.All)]
281 public string ColumnName
284 return "" + _columnName;
287 //Both are checked after the column is part of the collection
288 //TODO: Check Name duplicate
289 //TODO: check Name != null
294 [DataCategory ("Data")]
295 [DataSysDescription ("Indicates the type of data stored in this column.")]
296 [DefaultValue (typeof (string))]
297 [RefreshProperties (RefreshProperties.All)]
298 [TypeConverterAttribute (typeof (ColumnTypeConverter))]
305 // check if data already exists can we change the datatype
306 if(DataHasBeenSet == true)
307 throw new ArgumentException("The column already has data stored.");
309 // we want to check that the datatype is supported?
310 TypeCode typeCode = Type.GetTypeCode(value);
312 //Check AutoIncrement status, make compatible datatype
313 if(AutoIncrement == true) {
314 if(typeCode != TypeCode.Int16 &&
315 typeCode != TypeCode.Int32 &&
316 typeCode != TypeCode.Int64)
317 AutoIncrement = false;
326 /// <remarks>When AutoIncrement is set to true, there can be no default value.</remarks>
327 /// <exception cref="System.InvalidCastException"></exception>
328 /// <exception cref="System.ArgumentException"></exception>
329 [DataCategory ("Data")]
330 [DataSysDescription ("Indicates the default column value used when adding new rows to the table.")]
331 [TypeConverterAttribute (typeof (System.Data.DefaultValueTypeConverter))]
332 public object DefaultValue
335 return _defaultValue;
339 if ((this._defaultValue == null) || (!this._defaultValue.Equals(value)))
341 //If autoIncrement == true throw
344 throw new ArgumentException("Can not set default value while" +
345 " AutoIncrement is true on this column.");
350 tmpObj = DBNull.Value;
355 if ((this.DataType != typeof (object))&& (tmpObj != DBNull.Value))
359 //Casting to the new type
360 tmpObj= Convert.ChangeType(tmpObj,this.DataType);
362 catch (InvalidCastException)
364 throw new InvalidCastException("Default Value type is not compatible with" +
368 _defaultValue = tmpObj;
374 [DataCategory ("Data")]
375 [DataSysDescription ("Indicates the value that this column computes for each row based on other columns instead of taking user input.")]
377 [RefreshProperties (RefreshProperties.All)]
378 public string Expression
384 if ( value != null ) {
388 //Check the validate expression of ExpressionElement with string
389 expression = System.Data.ExpressionElement.ValidateExpression(expression);
391 if (expression != string.Empty)
398 [DataCategory ("Data")]
399 [DataSysDescription ("The collection that holds custom user information.")]
400 public PropertyCollection ExtendedProperties
403 return _extendedProperties;
407 [DataCategory ("Data")]
408 [DataSysDescription ("Indicates the maximum length of the value this column allows.")]
413 //Default == -1 no max length
417 //only applies to string columns
422 [DataCategory ("Data")]
423 [DataSysDescription ("Indicates the XML uri for elements stored in this column.")]
424 public string Namespace
434 //Need a good way to set the Ordinal when the column is added to a columnCollection.
436 [DataCategory ("Data")]
437 [DataSysDescription ("Indicates the index of this column in the Columns collection.")]
438 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
442 //value is -1 if not part of a collection
447 internal void SetOrdinal(int ordinal)
452 [DataCategory ("Data")]
453 [DataSysDescription ("Indicates the prefix used for this DataColumn in the xml representation.")]
465 [DataCategory ("Data")]
466 [DataSysDescription ("Indicates whether this column allows changes once a row has been added to the table.")]
467 [DefaultValue (false)]
479 [DataCategory ("Data")]
480 [DataSysDescription ("Returns the DataTable to which this column belongs.")]
481 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
482 public DataTable Table
490 [DataCategory ("Data")]
491 [DataSysDescription ("Indicates whether this column should restrict its values in the rows of the table to be unique.")]
492 [DefaultValue (false)]
493 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
500 //if Table == null then the UniqueConstraint is
501 //created on addition to the collection
503 //FIXME?: need to check if value is the same
504 //because when calling "new UniqueConstraint"
505 //the new object tries to set "column.Unique = True"
506 //which creates an infinite loop.
513 if (Expression != null && Expression != "")
514 throw new ArgumentException("Cannot change Unique property for the expression column.");
517 UniqueConstraint uc = new UniqueConstraint(this);
518 _table.Constraints.Add(uc);
525 ConstraintCollection cc = _table.Constraints;
526 //foreach (Constraint c in cc)
527 for (int i = 0; i < cc.Count; i++)
529 Constraint c = cc[i];
530 if (c is UniqueConstraint)
532 DataColumn[] cols = ((UniqueConstraint)c).Columns;
534 if (cols.Length == 1 && cols[0] == this)
536 if (!cc.CanRemove(c))
537 throw new ArgumentException("Cannot remove unique constraint '" + c.ConstraintName + "'. Remove foreign key constraint first.");
551 #endregion // Properties
557 protected internal void CheckNotAllowNull() {
561 protected void CheckUnique() {
566 /// Sets unique true whithout creating Constraint
568 internal void SetUnique()
575 internal void AssertCanAddToCollection()
577 //Check if Default Value is set and AutoInc is set
581 protected internal virtual void
582 OnPropertyChanging (PropertyChangedEventArgs pcevent) {
586 protected internal void RaisePropertyChanging(string name) {
590 /// Gets the Expression of the column, if one exists.
592 /// <returns>The Expression value, if the property is set;
593 /// otherwise, the ColumnName property.</returns>
595 public override string ToString()
597 if (expression != string.Empty)
598 return ColumnName + " + " + expression;
604 internal void SetTable(DataTable table) {
606 // this will get called by DataTable
607 // and DataColumnCollection
611 // Returns true if all the same collumns are in columnSet and compareSet
612 internal static bool AreColumnSetsTheSame(DataColumn[] columnSet, DataColumn[] compareSet)
614 if (null == columnSet && null == compareSet) return true;
615 if (null == columnSet || null == compareSet) return false;
617 if (columnSet.Length != compareSet.Length) return false;
619 foreach (DataColumn col in columnSet)
621 bool matchFound = false;
622 foreach (DataColumn compare in compareSet)
629 if (! matchFound) return false;
635 static internal int CompareValues (object val1, object val2, Type t, bool ignoreCase)
637 IComparer comparer = DBComparerFactory.GetComparer (t, ignoreCase);
638 return comparer.Compare (val1, val2);
641 #endregion // Methods