-1

我已经编写了一些代码来从字符串 datagridview 列中获取日期并将其设置为 datetime 对象,但它显示错误

foreach (DataGridViewRow r in dataGridView1.Rows)
{
    string day = r.Cells["l_date_from"].Value.ToString().Substring(0,2);
    string month = r.Cells["l_date_from"].Value.ToString().Substring(3,2);
    string year = r.Cells["l_date_from"].Value.ToString().Substring(6,4);

    string mydate_From = month + "/" + day + "/" + year;

    day = r.Cells["l_date_To"].Value.ToString().Substring(0, 2);
    month = r.Cells["l_date_To"].Value.ToString().Substring(3, 2);
    year = r.Cells["l_date_To"].Value.ToString().Substring(6, 4);
    string mydate_To = month + "/" + day + "/" + year;

    cmd.CommandText = "insert into " + table_Name + " (entry_no,invoice_number,invoice_date,sid,h_sr_no,hid,h_name,h_location,h_size1,h_size2,h_size_sqf,hRate,number_of_months,hTotal,from_date,to_date,hTotalAmount,advance,balance,e_date,e_uid,e_fid,transaction_code) values (" + txtEntryNo.Text + "," + txtInvoiceNo.Text + ",'" + txtDate.Value.ToString("MM/dd/yyyy") + "'," + Supplier_number + "," + r.Cells["l_sr"].Value.ToString() + "," + r.Cells["l_hid"].Value.ToString() + ",'" + r.Cells["l_h_name"].Value.ToString() + "','" + r.Cells["l_hLocation"].Value.ToString() + "'," + r.Cells["l_hsize1"].Value.ToString() + "," + r.Cells["l_hsize2"].Value.ToString() + "," + r.Cells["l_hsizesqf"].Value.ToString() + "," + r.Cells["l_rate"].Value.ToString() + "," + r.Cells["l_nom"].Value.ToString() + "," + r.Cells["l_total"].Value.ToString() + ",'" + mydate_From + "','" + mydate_To + "'," + txtTotal.Text + "," + txtAdvance.Text + "," + txtBalance.Text + ",'" + DateTime.Now.ToString("MM/dd/yyyy") + "'," + Global_.Functions_.Entry_UID_ + "," + Global_.Functions_.Entry_FID_ + ",'" + tra_code + "')";
    cmd.ExecuteNonQuery();
}

datagridview 列返回日期值,例如(“7/11/2013”​​),我想将此值设置为 Datetime 对象。

4

2 回答 2

1

除非您在其他地方使用字符串日期,否则您可以稍微改变您的逻辑。

而不是这样做

string mydate_From = month + "/" + day + "/" + year;

直接创建DateTime实例

var mydate_From = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day));

编辑

实际上,我认为这可以解决问题

var mydate_From = DateTime.ParseExact(
     r.Cells["l_date_from"].Value.ToString(), 
     "dd/MM/yyyy", 
     CultureInfo.InvariantCulture);

var mydate_To = DateTime.ParseExact(
     r.Cells["l_date_To"].Value.ToString(), 
     "dd/MM/yyyy", 
     CultureInfo.InvariantCulture);
于 2013-11-07T12:19:44.053 回答
0
DateTimeFormatInfo dateformat= new DateTimeFormatInfo();
dateformat.ShortDatePattern = "dd/MM/yyyy";
dateformat.DateSeparator = "/";
DateTime objDate = Convert.ToDateTime(strDate, dateformat);
于 2013-11-07T12:19:28.893 回答