2011-05-23 53 views
3

我想在DataGridView列中顯示TimeSpan字段,如hhmm。並允許用戶以這種格式編輯它。據我所知,我需要添加一些邏輯到CellFormatting,CellParsingCellValidating事件。所以我想我必須檢查列名,併爲那些需要處理它。將hhmm DataGridView單元格值轉換爲TimeSpan字段

但我怎麼能更好地解決這個代碼重用的目的?我可以創建一個自定義的DataGridViewColumn類,我可以把這個邏輯?這將如何實現?我看不到DataGridViewColumn類存在任何事件,所以不太確定在這裏做什麼。

+0

你如何將數據綁定到網格? – jparram 2011-07-06 19:42:42

回答

0

我想看看DataGridViewColumn.CellTemplate屬性,這是這種類型的:

public abstract class DataGridViewCell : DataGridViewElement, ICloneable, IDisposable 

擁有這些有趣的屬性:

Value: object 
ValueType: Type 
ValueTypeConverter: TypeConverter 

從那裏,我會看着TypeConverter類。

希望這會有所幫助,這就是我通過ILSpy查看大約2分鐘內收集到的信息。

0

也許這對你來說已經太遲了,但我想它會幫助別人。我昨天的問題幾乎一樣。 我通過創建類包裝到我的TimeSpan成員來解決它,在該成員中,我重寫了ToString方法(以便以首選格式顯示時間),並創建了Parse(String)方法,當用戶完成單元格編輯時會自動調用該方法。最後,爲了捕獲可能在Parse方法中生成的異常,爲DataGridView的DataError事件創建處理程序。 例如:

class TimeSpanDecorator 
{ 
    protected TimeSpan timeSpan; 
    public TimeSpanDecorator(TimeSpan ts) 
    { 
     timeSpan = ts; 
    } 
    public override string ToString() // return required TimeSpan view 
    { 
     return timeSpan.Hours + ":" + timeSpan.Minutes; 
    } 
    public static TimeSpanDecorator Parse(String value) // parse entered value in any way you want 
    { 
     String[] parts = value.Split(':'); 
     if (parts.Length != 2) 
      throw new ArgumentException("Wrong format"); 
     int hours = Int32.Parse(parts[0]); 
     int minutes = Int32.Parse(parts[1]); 
     TimeSpanDecorator result = new TimeSpanDecorator(new TimeSpan(hours, minutes, 0)); 
     if (result.timeSpan.Ticks < 0) 
      throw new ArgumentException("You should provide positive time value"); 
     return result; 
    } 
    //other members 
} 

internal partial class MainForm : Form 
{ 
    (...) 
    private void dataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e) 
    { 
     MessageBox.Show("Error occured: " + e.Exception.Message, "Warning!"); // showing generated argument exception 
     e.ThrowException = false; // telling form that we have processed the error 
    } 
} 

希望這會幫助任何人。