简体   繁体   English

将DateTime格式从一种形式更改为另一种形式

[英]Changing DateTime Format from one form to another

I wish to make the "tdate" format as "d, MMM, yyyy" and then send it from one form which has a data grid view to a different form which contains a textbox. 我希望将“ tdate”格式设置为“ d,MMM,yyyy”,然后将其从具有数据网格视图的一种表单发送到包含文本框的另一种表单。

So far I tried to make it as: 到目前为止,我试图做到:

 frm.txtDate.Text = (this.dgvEvents.CurrentRow.Cells[2].Value.ToString("d, MMM, yyyy"));

This is the code of the class :- 这是此类的代码:-

public int CreateTicket(string tName, DateTime tDate, string type, string venue)
{
    EventTicketEntities database = new EventTicketEntities();
    Ticket t = new Ticket();
    t.TicketName = tName;
    t.TicketDate = tDate;
    t.TicketType = type;
    t.TicketVenue = venue;
    database.Tickets.Add(t);//We ADD our promoter to our advertiser table!
    return database.SaveChanges(); //returns the affected rows ....
}

And this code is to show a new form when the "Proceed" button is clicked. 当单击“继续”按钮时,此代码将显示一个新表单。

public void btnProceed_Click(object sender, EventArgs e)
{
    ticketForm frm = new ticketForm();

     frm.txtName.Text = (this.dgvEvents.CurrentRow.Cells[1].Value.ToString());
     frm.txtDate.Text = (this.dgvEvents.CurrentRow.Cells[2].Value.ToString());
     frm.txtType.Text = (this.dgvEvents.CurrentRow.Cells[3].Value.ToString());
     frm.txtVenue.Text = (this.dgvEvents.CurrentRow.Cells[4].Value.ToString());
    //pass selected index of combobox 

    frm.Show();
}

Cell.Value is of type object , you need to cast it to DateTime to apply customized formatting. Cell.Valueobject类型,您需要将其Cell.ValueDateTime才能应用自定义格式。

((DateTime)this.dgvEvents.CurrentRow.Cells[2].Value)
                   .ToString("d, MMM, yyyy", CultureInfo.InvariantCulture);

Also supply CultureInfo.InvariantCulture to keep your date separator , . 同时供应CultureInfo.InvariantCulture ,让您的日期分隔符,

This would only work, if the data in your your cell is DateTime type to begin with, otherwise you will end up with exception 仅当您单元格中的数据以DateTime类型开头时,此方法才有效,否则最终将出现异常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM