tags:

views:

763

answers:

2

I have a DataTable that I have populated via the Dataset.ReadXML() method. I am trying to programatically determine the maximum field lengths for each column in the datatable. The MaxLength value for all of my columns is always at the default of -1.

Any thoughts or examples on how to determine the proper max length? maybe based on the actual data in the table? (Datatable can be in the 25 column by 200,000+ row range)

C# 2.0

+2  A: 

I believe it would be DataSet.DataTable.Columns[0].MaxLength

mikemurf22
I guess it could be DataSet.DataTables["tableName"].Columns["columnName"].MaxLength.
shahkalpesh
Except that MaxLength always seems to be -1 (for unlimited?)
John
Yes, -1 is no max length. Check out http://msdn.microsoft.com/en-us/library/system.data.datacolumn.maxlength.aspx
Jay Riggs
According to the doco. "If the column has no maximum length, the value is –1 (default)." So I think it would be infinite.
mikemurf22
+2  A: 

I don't quite understand what your objectives are - what are you trying to find out? The number of bytes a given column will use (e.g. 4 for INT, 8 for BIGINT and so forth), or the actual current maximum length of e.g. all strings in column "ColA" ?

As for the INT and other numerical and boolean types - those have a fixed system-given length - no problems there.

Unless your XML has a schema (XSD file) which limits the string lengths, the string fields from an XML can be any length, really, so after reading them in, your DataTable can't really know what the defined max length can be.

All you can do is loop over all rows in your DataTable and determine the current length of the strings, and get the maximum of those current lengths, as your frame of reference.

Does that help at all?

Marc

marc_s
Your answer confirms what I have been finding. I guess I was hopingthat there was a different answer.. Oh well.Thanks
John
The ultimate objective is to determine the max length of strings coming back via a web service and then create a SQL script that would make the equivalent fields in a new SQL table.
John
I guess in this case, you'd just have to monitor the maximum length for every string, and then make an educated guess as to how much extra length you might want to add (e.g. round up to the nearest 100 chars or something like that).
marc_s