2012-05-17 1 views
3

데이터베이스의 데이터를 채우는 datagridview가 있으며 "MMddyyyy"및 "hhmmss"형식의 날짜와 시간이있는 열이 있는데, 원하는 작업은 datagridview가로드 될 때입니다. , 나는이 형식을 다른 형식으로, 예를 들어 dd-MM-yy로, hh-mm-ss로 변경하고 싶다. 나는 그것을 할 수있는 방법을 안내 할 수 있는지 궁금해했다. 나는 gridview.columns하여이 작업을 수행 할 수 없었던 [X] .defaultcellstyle.format = "DD-MM-YY"나는 오류 아무것도하지만이있는 gridview에서 변경되지 얻을 위와 ...C# DataGridView 날짜 시간 형식의 열

감사합니다

참고 : 나는 :-( 더 구문 문제

답변

8

마이크로 소프트가 없습니다 ..뿐만 아니라 데이터베이스에 컬럼 길이를 변경할 수있는 옵션을 가지고 있겠지 곳 일자가 열입니다 (당신이 CellFormatting 이벤트를 가로 챌 제안 다시 형식을 지정하려는 경우) :

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    // If the column is the DATED column, check the 
    // value. 
    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "DATED") 
    { 
     ShortFormDateFormat(e); 
    } 
} 

private static void ShortFormDateFormat(DataGridViewCellFormattingEventArgs formatting) 
{ 
    if (formatting.Value != null) 
    { 
     try 
     { 
      DateTime theDate = DateTime.Parse(formatting.Value.ToString()); 
      String dateString = theDate.ToString("dd-MM-yy");  
      formatting.Value = dateString; 
      formatting.FormattingApplied = true; 
     } 
     catch (FormatException) 
     { 
      // Set to false in case there are other handlers interested trying to 
      // format this DataGridViewCellFormattingEventArgs instance. 
      formatting.FormattingApplied = false; 
     } 
    } 
} 
+0

덕분에, 내가 없어진 것을 볼 수 ... – user1063108

+0

코드 당신을 단축하려면 (e.ColumnIndex == 3) ...) –

2

DataGridView 포매팅의 sintax는 DateTime과 약간 다르지만 동일한 결과를 얻을 수 있습니다. MM : SS와 난 단지 시간과 분 보여주고 싶은 내 예에서 내가 HH 기본 프로그램으로 것으로, 시간 collumn이

yourDataGridView.Columns["Time"].DefaultCellStyle.Format = @"hh\:mm"; 
+0

이것은 DateTime 형식으로는 작동하지 않습니다. 그래서 나는 대답을 받아 들였다. 흥미로운 점은 디자이너를 사용하여 열을 편집 한 다음 셀 스타일을 선택한 다음 서식을 편집하는 경우 제한된 선택 만있을뿐입니다. 예를 들어 날짜를 프랑스어 로켈 형식 ("dd/MM/yyyy")으로 포맷 할 수 없으면 제안 된 선택 사항이 영어 로켈에 바인딩됩니다. –