How do I display MM/dd/yyyy (no time) in my DataGridView column?

后端 未结 7 478
臣服心动
臣服心动 2021-01-15 18:41

I need help on my DataGridView column date format. I want the date to be \"MM/dd/yyyy\". I dont need the time.

How can this be done programmatically?

相关标签:
7条回答
  • 2021-01-15 19:14

    for example.

      gridView.DefaultCellStyle.Format = "dd/MM/yyyy";
    

    try this

      gridView.Columns[3].DefaultCellStyle.Format = "dd/MM/yyyy";
    
    0 讨论(0)
  • 2021-01-15 19:18

    The easiest way is to use DateTime.ToShortDateString() or DateTime.ToLongDateString()

    If neither of those formats works take a look at DateTime.ToString(string)

    0 讨论(0)
  • 2021-01-15 19:18

    Make sure that the date stored in the database is in DateTime or Date DataType.

    If the datatype of that field is not datetime or date then it could not be formatted using that format. Either convert the datatype into datetype in table schema or convert the date in sql query.

    Select Cast(entry_datetime As DateTime)...
    

    If the field datatype is datetime and still it is showing that result then you can format the date in your sql query directly.

    Select CONVERT(VARCHAR(10), entry_datetime, 101) As EntryDate,....
    
    0 讨论(0)
  • 2021-01-15 19:20

    You should use DataFormatString as {0:MM/dd/yyyy} on the column to get desired date format.

    0 讨论(0)
  • 2021-01-15 19:35

    After you set the DataSource of the DataGridView, set the desired format of the column:

    dataGridView1.Columns["dateReceived"].DefaultCellStyle.Format = "MM/dd/yyyy";
    
    0 讨论(0)
  • 2021-01-15 19:36

    If you're trying to format a databound column, you should use DefaultCellStyle.Format. Be sure the value of Format attribute isn't being overwritten on Designer.

    The code below works fine:

            Random rnd = new Random();
    
            dataGridView1.Columns.Clear();
            dataGridView1.Columns.Add("colDate", "Random Date");
            dataGridView1.Columns["colDate"].DefaultCellStyle.Format = "MM/dd/yyyy";
            dataGridView1.Columns["colDate"].DataPropertyName = "Date";
    
            DataTable dt = new DataTable();
            dt.Columns.Add("Date", typeof(DateTime));
            for (int i = 1; i <= 10; i++)
            {
                DataRow row = dt.NewRow();
                row["Date"] = DateTime.Now.AddDays(10 - rnd.Next(20));
                dt.Rows.Add(row);
            }
            dataGridView1.DataSource = dt;
    
    0 讨论(0)
提交回复
热议问题