Click here to Skip to main content
15,890,557 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I wrote a program to split the Date and Time as 2 different columns from 1 column.
If i have a blank value in datetime field, the split functionality is not working.
It's giving error stating "FormatException was unhandled" for below mentioned line:

DateTime Time = Convert.ToDateTime(column[i].ToString());

Please let me know where i have to correct.

Total code for that functionality is:

private void btnSplit_Click(object sender, EventArgs e)
{
DataGridViewTextBoxColumn dgvcdate = new DataGridViewTextBoxColumn();
dgvcdate.Name = cmbColumnCombo.Text;
dgvcdate.HeaderText = cmbColumnCombo.Text;
dataGridView1.Columns.Add(dgvcdate);

DataGridViewTextBoxColumn dgvctime = new DataGridViewTextBoxColumn();
dgvctime.Name = txtColumnName.Text.Replace(" ", "");
dgvctime.HeaderText = txtColumnName.Text;
dataGridView1.Columns.Add(dgvctime);

for (int RowCount = 1; RowCount <= strfile.Length - 1; RowCount++)
{
if (strfile[RowCount].ToString() != "")
{
if (RowCount != 0)
{
string[] column = strfile[RowCount].Split('þ');
for (int i = 1; i < column.Length - 1; i++)
{
if (cmbColumnCombo.SelectedIndex == ((i - 1) / 2))
{
if (column[i].ToString() != "\u0014")
{
dataGridView1.Rows.Add();
DateTime Time = Convert.ToDateTime(column[i].ToString());
dataGridView1.Rows[RowCount - 1].Cells[txtColumnName.Text.Replace(" ", "")].Value = Time.ToString("HH:mm:ss");
dataGridView1.Rows[RowCount - 1].Cells[cmbColumnCombo.Text].Value = Time.ToString("dd/MM/yyyy");
//dataGridView1.Rows[RowCount - 1].Cells[cmbColumn1.Text].Value += column[i].ToString();
}
}
}
}
}
}
}
Posted
Comments
Suvendu Shekhar Giri 27-Jan-16 1:26am    
Why don't you validate blank values?
Member 8010354 27-Jan-16 2:19am    
Can you please explain clearly? Nevermind, i'm new to .net

First Check if the value you get is null

C#
if(column[i]!=null)
{
//convert to datetime
}


hope it helps you..
 
Share this answer
 
Try this:
C#
DateTime dt;

DateTime Time =  DateTime.TryParse(ToDateTime(column[i].ToString(), out dt));

if(dt == null)
{
     // handle invalid date
     // throw error ?
     // use 'continue to proceed with column entry ?
}
else
{
     // valid date present in 'dt
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900