Sunday, May 23, 2010

DataColumn.MaxLength not working in C#

DataColumn.MaxLength

Visual Studio Intellisense: Gets or Sets the maximum length of a text column.
MSDN: The maximum length of the column in characters. If the column has no maximum length, the value is –1 (default).

But most of the developers didn't able to get the desired result. It always returns -1. Microsoft has confirmed that this is a bug in the Microsoft products.

To resolve this, you need to set the "MissingSchemaAction" of "SqlDataAdapter" object. If you did not have it set, the ColumnLength property always returns -1.

Reference: http://support.microsoft.com/kb/317175

Example:

string strQuery = "SELECT * FROM tbl_MyTable";
objConn = new SqlConnection(strConnString);
objConn.Open();
objCmd = new SqlCommand(strQuery, objConn);
objDA = new SqlDataAdapter(objCmd);
objDA.MissingSchemaAction = MissingSchemaAction.AddWithKey;
objDS = new DataSet();
int iCount = objDA.Fill(objDS);

0 comments: