也許這對你來說已經太遲了,但我想它會幫助別人。我昨天的問題幾乎一樣。 我通過創建類包裝到我的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
}
}
希望這會幫助任何人。
你如何將數據綁定到網格? – jparram 2011-07-06 19:42:42