Type of value has a mismatch with column type

After migrating to VS2005 / .net 2 The following code gets me a server error:


          public DataTable CreateDataSource(DataSet ds,int page_current, int page_products)
        {

               int startIndex = page_current * page_products;

               DataTable dt = new DataTable();

               for (int i = 0; i < ds.Tables[0].Columns.Count ; i++)
            {    
                    dt.Columns.Add(ds.Tables[0].Columns[i].ColumnName, ds.Tables[0].Columns[i].GetType() );
               }

            for (int i = startIndex; i < (startIndex + page_products); i++)
            {

                if (i < ds.Tables[0].Rows.Count)
                {
                    DataRow dr = dt.NewRow();

                    for (int k = 0; k < dt.Columns.Count; k++)
                    {
                        dr[k] = ds.Tables[0].Rows[i][k];
                    }

                    dt.Rows.Add(dr);
                }
                else
                    i = startIndex + page_products;

            }
               return dt;
          }


The error is:

Server Error in '/' Application.
--------------------------------------------------------------------------------

Type of value has a mismatch with column type
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Type of value has a mismatch with column type

Source Error:


Line 289:                         DataRow dr = dt.NewRow();
Line 290:                         for (int k=0;k<dt.Columns.Count;k++){
Line 291:                              dr[k] = ds.Tables[0].Rows[i][k];
Line 292:                         }
Line 293:                         dt.Rows.Add(dr);
 


Any ideas why this is happening? It works perfectly under vs2003.

Thanks!
infodiggerAsked:
Who is Participating?
 
e1vConnect With a Mentor Commented:
I think the problem is the line

  dt.Columns.Add(ds.Tables[0].Columns[i].ColumnName, ds.Tables[0].Columns[i].GetType() );

because the GetType() there will always return DataColumn. Instead you should use .DataType like

  dt.Columns.Add(ds.Tables[0].Columns[i].ColumnName, ds.Tables[0].Columns[i].DataType);


Why It did work in 2003 I don't know...

0
 
infodiggerAuthor Commented:
Thank you so much for the fast reply! It worked perfect!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.