也许这对你来说已经太迟了,但我想它会帮助别人。我昨天的问题几乎一样。 我通过创建类包装到我的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