locked
Cast error when adding a row RRS feed

  • Question

  • Hello everybody,

    I am writing an application that stores its data in an XML file.

    A datatable used to show the data is defined as this :

    dt.Columns.Add(new DataColumn("repIntitule", typeof(String)));
    dt.Columns.Add(new DataColumn("repDate", typeof(DateTime)));
    dt.Columns.Add(new DataColumn("repIntervalle", typeof(Int32)));
    dt.Columns.Add(new DataColumn("DateCible", typeof(long), "Convert(repDate, System.Int32) + repIntervalle"));

    In fact, DateCible is calculated by adding the integer repIntervalle to the date repDate, to indicate the end of a date interval. It seems I did not formulate the expression (the calculation formula) correctly, this can constitute a secondary question that is about to arise as main question after the one I am going to ask (supposing the answer to the following question does not constitute an answer about the formula expression).

    I get an exception on the last instruction hereafter, dt.Rows.Add : invalid cast of DateTime to Int32. I have some difficulty to understand that all the casts beforewards are done without any difficulty, and the problem arises when adding the datarow to the datatable, without any precision about which column is concerned. Can anybody bring some light in this topic ?


    DataRow nr = dt.NewRow();
    nr[0] = (string) strIntitule;
    nr[1] = (DateTime) dat;
    nr[2] = (Int32) ervalle;
    nr[3] = (Int64) ticks;
    int n;   // later another question about this n
    dt.Rows.Add(nr);

    As the exception is speaking about an Int32, I precise that the value of ervalle is 35.

     

    Tuesday, May 3, 2011 8:11 PM

Answers

  • Hi Gloops,

    Based on your code, I think you have misunderstood the DataColumn.Expression Property with "convert".

    Here is a link about  DataColumn.Expression Property you can refer to: http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx

    In the link, it says as follows:

    All conversions are valid with the following exceptions: Boolean can be coerced to and from Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, String and itself only. Char can be coerced to and from Int32, UInt32, String, and itself only. DateTime can be coerced to and from String and itself only. TimeSpan can be coerced to and from String and itself only.

    So, you cannot convert DateTime type to int in the DataColumn.Expression as the error message describes. As a workaround, to write your own convertion method. I think you can do as follows:

     

     private void button1_Click(object sender, EventArgs e)
      {
       DataTable dt = new DataTable();
       dt.Columns.Add(new DataColumn("repIntitule", typeof(String)));
       dt.Columns.Add(new DataColumn("repDate", typeof(DateTime)));
       dt.Columns.Add(new DataColumn("repIntervalle", typeof(Int32)));
       dt.Columns.Add(new DataColumn("DateCible", typeof(long)));
    
       DataRow nr = dt.NewRow();
       nr[0] = "ss";
       nr[1] = new DateTime(2011,2,2,3,3,3);
       nr[2] = 22;
       nr[3] = DateTimeToInt((DateTime)nr[1]) + (int)nr[2];
       dt.Rows.Add(nr);
    
       this.dataGridView1.DataSource = dt;
      }
    
      private int DateTimeToInt(DateTime datetime)
      {
       //you can do how datetime convert to int value as you want here
    int result = 0; result = datetime.Year + datetime.Month + datetime.Day; return result; }

     In addtion, the Convert.ToInt32 Method (DateTime) in not supported. It will always throw InvalidCaseException.

    Here is a official document you can refer to: http://msdn.microsoft.com/en-us/library/ch56d3w9(v=VS.100).aspx


    Vin Jin [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.


    • Marked as answer by Gloops Saturday, May 7, 2011 9:49 AM
    Thursday, May 5, 2011 6:48 AM

All replies

  • try:

    nr[1] = Convert.ToDateTime(dat); //as long as the dat is a string of date or time value
    


    Mitja
    Tuesday, May 3, 2011 8:59 PM
  • I don't know if it happened when you posted this question or if it's your actual code and causing the error, but you've got some erroneous quotes in there which would result in you passing a String to the last call instead of a Long Integer:

     

    dt.Columns.Add(new DataColumn("DateCible", typeof(long), "Convert(repDate, System.Int32) + repIntervalle"));
    
    Try removing the quotation marks from before "Convert" and after "repIntervalle"...

     


    Tuesday, May 3, 2011 9:01 PM
  • Hi Gloops,

    Based on your code, I think you have misunderstood the DataColumn.Expression Property with "convert".

    Here is a link about  DataColumn.Expression Property you can refer to: http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx

    In the link, it says as follows:

    All conversions are valid with the following exceptions: Boolean can be coerced to and from Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, String and itself only. Char can be coerced to and from Int32, UInt32, String, and itself only. DateTime can be coerced to and from String and itself only. TimeSpan can be coerced to and from String and itself only.

    So, you cannot convert DateTime type to int in the DataColumn.Expression as the error message describes. As a workaround, to write your own convertion method. I think you can do as follows:

     

     private void button1_Click(object sender, EventArgs e)
      {
       DataTable dt = new DataTable();
       dt.Columns.Add(new DataColumn("repIntitule", typeof(String)));
       dt.Columns.Add(new DataColumn("repDate", typeof(DateTime)));
       dt.Columns.Add(new DataColumn("repIntervalle", typeof(Int32)));
       dt.Columns.Add(new DataColumn("DateCible", typeof(long)));
    
       DataRow nr = dt.NewRow();
       nr[0] = "ss";
       nr[1] = new DateTime(2011,2,2,3,3,3);
       nr[2] = 22;
       nr[3] = DateTimeToInt((DateTime)nr[1]) + (int)nr[2];
       dt.Rows.Add(nr);
    
       this.dataGridView1.DataSource = dt;
      }
    
      private int DateTimeToInt(DateTime datetime)
      {
       //you can do how datetime convert to int value as you want here
    int result = 0; result = datetime.Year + datetime.Month + datetime.Day; return result; }

     In addtion, the Convert.ToInt32 Method (DateTime) in not supported. It will always throw InvalidCaseException.

    Here is a official document you can refer to: http://msdn.microsoft.com/en-us/library/ch56d3w9(v=VS.100).aspx


    Vin Jin [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.


    • Marked as answer by Gloops Saturday, May 7, 2011 9:49 AM
    Thursday, May 5, 2011 6:48 AM
  • Oh, and I already had an answer three days ago ?

    Sorry, I thought I should be alerted by mail.

    Well, I even see I have different answers, at different levels of action.

    Thank you very much, I am going to look at all that.

     

    Friday, May 6, 2011 9:18 PM
  • Well, I am going to tempt and be synthetic.
    The documentation gives expression of type String, this was what encouraged me to put quotes around it, but it gives nothing good. With no quotes, it appears I do not have access to the names of the other columns, what I feel surprising. Is the solution to ignore the expression notion ?
    Anyway vin proposed not to use it in this project, and this led to a solution.
    After the initialization I had
                            long ticks = (long)(Convert.ToDateTime(r["repDate"])).AddDays(ervalle).Ticks;
                            nr[3] = (Int64) ticks;
    and this does not raise any exception.

    It works.
    At the end of all that I feel "oh well, that simple, and to be able to say it, it appears necessary to have such a background ..."

    Now, I have to understand why some things that worked properly with the application refering to a Dataset defined on SQL Server and then saved to XML, do not work now that the application does not refer to SQL Server any more (in order to facilitate the deployment).

    Anyway I first have to properly define two datatables, one for the display form that uses a custom control, and one for the user seizing, that uses a datagrid. The first one must include the date end column, but not the other one.

    So, understanding what happened and led to an exception was a step in the process. Thank you to have helped me for that.

    Saturday, May 7, 2011 9:48 AM