Reputation: 497
I am running into the error 'string' does not contain a definition for 'ToDateTime'
during the part of my code that is making sure the current date value is populated. Here are the pieces of code:
public class LegalTransactionRec
{
public string AccountNumber { get; set; }
public string CostAmount { get; set; }
public string SSN { get; set; }
public int BatchID { get; set; }
public Attorney Attorney { get; set; }
public DateTime TransactionDate { get; set; }
public string Description { get; set; }
public int TransactionCode { get; set; }
}
Its going down right here:
TransactionDate = Form1.CheckDate(xlRange.Cells[i, 2].Value2.ToDateTime())
Here is the function that is checking to make sure the field is populated:
public static DateTime CheckDate(DateTime tranDate)
{
DateTime date;
if (tranDate == null)
{
throw new System.ArgumentException("Value cannot be null", "original");
}
else
{
date = tranDate;
}
return date;
}
EDIT: Code for xlRange:
try
{
//workbook = excelApp.Workbooks.Open(txtbxFilename.Text); View above comment
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range xlRange = worksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
lstTran.Add(new LegalTransactionRec()
{
AccountNumber = Form1.CleanString(xlRange.Cells[i, 1].Value2.ToString()),
CostAmount = Form1.TryToParse(Form1.CleanAmount(xlRange.Cells[i, 3].Value2.ToString())),
SSN = Form1.CleanString(xlRange.Cells[i, 6].Value2.ToString()),
TransactionDate = Form1.CheckDate(xlRange.Cells[i, 2].Value2.ToDateTime()),
Description = xlRange.Cells[i, 8].Value2.ToString(),
TransactionCode = xlRange.Cells[i, 4].Value2.ToInt() //Work on the CheckNull function later
});
}
}
}
Any help would be greatly appreciated.
Upvotes: 0
Views: 1543
Reputation: 63772
Well, Value2 contains a string, plain an simple. You want to use something like this:
static DateTime ConvertToDateTime(object obj)
{
if (obj == null)
throw new ArgumentNullException();
return (DateTime)obj;
}
And then just call
ConvertToDateTime(xlRange.Cells[i, 2].Value);
to get the date time.
Or, if Value
still returns a string, you can do
static DateTime ConvertToDateTime(string str)
{
if (string.IsNullOrEmpty(str))
throw new ArgumentNullException();
return DateTime.Parse(str);
}
You may have to call it like this:
ConvertToDateTime(xlRange.Cells[i, 2].Value as string);
Upvotes: 3