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;
22 namespace System.Data {
23 internal delegate void DelegateColumnValueChange(DataColumn column, DataRow row, object proposedValue);
26 /// Summary description for DataColumn.
31 [DefaultMember ("Item")]
32 [DefaultProperty ("ColumnName")]
33 [DesignTimeVisible (false)]
34 public class DataColumn : MarshalByValueComponent
38 //used for constraint validation
39 //if an exception is fired during this event the change should be canceled
40 internal event DelegateColumnValueChange ValidateColumnValueChange;
42 //used for FK Constraint Cascading rules
43 internal event DelegateColumnValueChange ColumnValueChanging;
48 private bool _allowDBNull = true;
49 private bool _autoIncrement = false;
50 private long _autoIncrementSeed = 0;
51 private long _autoIncrementStep = 1;
52 private long _nextAutoIncrementValue = 0;
53 private bool dataHasBeenSet = false;
54 private string _caption = null;
55 private MappingType _columnMapping = MappingType.Element;
56 private string _columnName = null;
57 private Type _dataType = Type.GetType ("System.String");
58 private object _defaultValue = DBNull.Value;
59 private string expression = "";
60 private PropertyCollection _extendedProperties = new PropertyCollection ();
61 private int maxLength = -1; //-1 represents no length limit
62 private string nameSpace = "";
63 private int _ordinal = -1; //-1 represents not part of a collection
64 private string prefix = "";
65 private bool readOnly = false;
66 private DataTable _table = null;
67 private bool unique = false;
77 //TODO: Ctor init vars directly
78 public DataColumn(string columnName): this()
80 ColumnName = columnName;
83 public DataColumn(string columnName, Type dataType): this(columnName)
85 if(dataType == null) {
86 throw new ArgumentNullException("dataType can't be null.");
93 public DataColumn( string columnName, Type dataType,
94 string expr): this(columnName, dataType)
96 if (expr != null) Expression = expr;
99 public DataColumn(string columnName, Type dataType,
100 string expr, MappingType type): this(columnName, dataType, expr)
102 ColumnMapping = type;
108 [DataCategory ("Data")]
109 [DataSysDescription ("Indicates whether null values are allowed in this column.")]
110 [DefaultValue (true)]
111 public bool AllowDBNull
117 //TODO: If we are a part of the table and this value changes
118 //we need to validate that all the existing values conform to the new setting
126 //if Value == false case
129 if (_table.Rows.Count > 0)
131 bool nullsFound = false;
132 for(int r = 0; r < _table.Rows.Count; r++) {
133 DataRow row = _table.Rows[r];
134 if(row.IsNull(this)) {
140 //TODO: Validate no null values exist
141 //do we also check different versions of the row??
145 _allowDBNull = value;
150 /// Gets or sets a value indicating whether the column automatically increments the value of the column for new rows added to the table.
153 /// If the type of this column is not Int16, Int32, or Int64 when this property is set,
154 /// the DataType property is coerced to Int32. An exception is generated if this is a computed column
155 /// (that is, the Expression property is set.) The incremented value is used only if the row's value for this column,
156 /// when added to the columns collection, is equal to the default value.
158 [DataCategory ("Data")]
159 [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.")]
160 [DefaultValue (false)]
161 [RefreshProperties (RefreshProperties.All)]
162 public bool AutoIncrement
165 return _autoIncrement;
170 //Can't be true if this is a computed column
171 if (Expression != string.Empty)
173 throw new ArgumentException("Can not Auto Increment a computed column.");
176 //If the DataType of this Column isn't an Int
178 TypeCode typeCode = Type.GetTypeCode(_dataType);
179 if(typeCode != TypeCode.Int16 &&
180 typeCode != TypeCode.Int32 &&
181 typeCode != TypeCode.Int64)
183 _dataType = typeof(Int32);
186 _autoIncrement = value;
190 [DataCategory ("Data")]
191 [DataSysDescription ("Indicates the starting value for an AutoIncrement column.")]
193 public long AutoIncrementSeed
196 return _autoIncrementSeed;
199 _autoIncrementSeed = value;
200 _nextAutoIncrementValue = _autoIncrementSeed;
204 [DataCategory ("Data")]
205 [DataSysDescription ("Indicates the increment used by an AutoIncrement column.")]
207 public long AutoIncrementStep
210 return _autoIncrementStep;
213 _autoIncrementStep = value;
217 internal void UpdateAutoIncrementValue (long value)
219 if(value > _nextAutoIncrementValue) {
220 _nextAutoIncrementValue = value;
221 AutoIncrementValue ();
225 internal long AutoIncrementValue ()
227 long currentValue = _nextAutoIncrementValue;
228 _nextAutoIncrementValue += AutoIncrementStep;
232 internal bool DataHasBeenSet {
234 return dataHasBeenSet;
237 dataHasBeenSet = value;
241 [DataCategory ("Data")]
242 [DataSysDescription ("Indicates the default user-interface caption for this column.")]
243 public string Caption
255 [DataSysDescription ("Indicates how this column persists in XML: as an attribute, element, simple content node, or nothing.")]
256 [DefaultValue (MappingType.Element)]
257 public virtual MappingType ColumnMapping
260 return _columnMapping;
263 _columnMapping = value;
267 [DataCategory ("Data")]
268 [DataSysDescription ("Indicates the name used to look up this column in the Columns collection of a DataTable.")]
269 [RefreshProperties (RefreshProperties.All)]
271 public string ColumnName
274 return "" + _columnName;
277 //Both are checked after the column is part of the collection
278 //TODO: Check Name duplicate
279 //TODO: check Name != null
284 [DataCategory ("Data")]
285 [DataSysDescription ("Indicates the type of data stored in this column.")]
286 [DefaultValue (typeof (string))]
287 [RefreshProperties (RefreshProperties.All)]
294 // check if data already exists can we change the datatype
295 if(DataHasBeenSet == true)
296 throw new ArgumentException("The column already has data stored.");
298 // we want to check that the datatype is supported?
299 TypeCode typeCode = Type.GetTypeCode(value);
301 //Check AutoIncrement status, make compatible datatype
302 if(AutoIncrement == true) {
303 if(typeCode != TypeCode.Int16 &&
304 typeCode != TypeCode.Int32 &&
305 typeCode != TypeCode.Int64)
306 AutoIncrement = false;
315 /// <remarks>When AutoIncrement is set to true, there can be no default value.</remarks>
316 /// <exception cref="System.InvalidCastException"></exception>
317 /// <exception cref="System.ArgumentException"></exception>
318 [DataCategory ("Data")]
319 [DataSysDescription ("Indicates the default column value used when adding new rows to the table.")]
320 public object DefaultValue
323 return _defaultValue;
327 //If autoIncrement == true throw
330 throw new ArgumentException("Can not set default value while" +
331 " AutoIncrement is true on this column.");
334 //Will throw invalid cast exception
335 //if value is not the correct type
336 //FIXME: some types can be casted
337 if (value.GetType() != _dataType)
339 throw new InvalidCastException("Default Value type is not compatible with" +
343 _defaultValue = value;
348 [DataCategory ("Data")]
349 [DataSysDescription ("Indicates the value that this column computes for each row based on other columns instead of taking user input.")]
351 [RefreshProperties (RefreshProperties.All)]
352 public string Expression
358 //TODO: validation of the expression
359 expression = value; //Check?
361 if (expression != string.Empty)
367 [DataCategory ("Data")]
368 [DataSysDescription ("The collection that holds custom user information.")]
369 public PropertyCollection ExtendedProperties
372 return _extendedProperties;
376 [DataCategory ("Data")]
377 [DataSysDescription ("Indicates the maximum length of the value this column allows.")]
382 //Default == -1 no max length
386 //only applies to string columns
391 [DataCategory ("Data")]
392 [DataSysDescription ("Indicates the XML uri for elements stored in this column.")]
393 public string Namespace
403 //Need a good way to set the Ordinal when the column is added to a columnCollection.
405 [DataCategory ("Data")]
406 [DataSysDescription ("Indicates the index of this column in the Columns collection.")]
407 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
411 //value is -1 if not part of a collection
416 internal void SetOrdinal(int ordinal)
421 [DataCategory ("Data")]
422 [DataSysDescription ("Indicates the prefix used for this DataColumn in the xml representation.")]
434 [DataCategory ("Data")]
435 [DataSysDescription ("Indicates whether this column allows changes once a row has been added to the table.")]
436 [DefaultValue (false)]
448 [DataCategory ("Data")]
449 [DataSysDescription ("Returns the DataTable to which this column belongs.")]
450 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
451 public DataTable Table
459 [DataCategory ("Data")]
460 [DataSysDescription ("Indicates whether this column should restrict its values in the rows of the table to be unique.")]
461 [DefaultValue (false)]
462 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
469 //if Table == null then the UniqueConstraint is
470 //created on addition to the collection
472 //FIXME?: need to check if value is the same
473 //because when calling "new UniqueConstraint"
474 //the new object tries to set "column.Unique = True"
475 //which creates an infinite loop.
482 if (Expression != null && Expression != "")
483 throw new ArgumentException("Cannot change Unique property for the expression column.");
486 UniqueConstraint uc = new UniqueConstraint(this);
487 _table.Constraints.Add(uc);
494 ConstraintCollection cc = _table.Constraints;
495 //foreach (Constraint c in cc)
496 for (int i = 0; i < cc.Count; i++)
498 Constraint c = cc[i];
499 if (c is UniqueConstraint)
501 DataColumn[] cols = ((UniqueConstraint)c).Columns;
503 if (cols.Length == 1 && cols[0] == this)
505 if (!cc.CanRemove(c))
506 throw new ArgumentException("Cannot remove unique constraint '" + c.ConstraintName + "'. Remove foreign key constraint first.");
520 #endregion // Properties
526 protected internal void CheckNotAllowNull() {
530 protected void CheckUnique() {
535 /// Sets unique true whithout creating Constraint
537 internal void SetUnique()
544 internal void AssertCanAddToCollection()
546 //Check if Default Value is set and AutoInc is set
550 protected internal virtual void
551 OnPropertyChanging (PropertyChangedEventArgs pcevent) {
555 protected internal void RaisePropertyChanging(string name) {
559 /// Gets the Expression of the column, if one exists.
561 /// <returns>The Expression value, if the property is set;
562 /// otherwise, the ColumnName property.</returns>
564 public override string ToString()
566 if (expression != string.Empty)
567 return ColumnName + " + " + expression;
573 internal void SetTable(DataTable table) {
575 // this will get called by DataTable
576 // and DataColumnCollection
580 // Returns true if all the same collumns are in columnSet and compareSet
581 internal static bool AreColumnSetsTheSame(DataColumn[] columnSet, DataColumn[] compareSet)
583 if (null == columnSet && null == compareSet) return true;
584 if (null == columnSet || null == compareSet) return false;
586 if (columnSet.Length != compareSet.Length) return false;
588 foreach (DataColumn col in columnSet)
590 bool matchFound = false;
591 foreach (DataColumn compare in compareSet)
598 if (! matchFound) return false;
604 #endregion // Methods