【发布时间】:2009-03-11 14:03:49
【问题描述】:
我有一个通过通用列表绑定到的 gridview。我自己设置了所有列。我只是想:
在编辑行时捕获事件 PRE 格式错误 - 通过隐藏字段获取行信息 - 并保持
我相信这一定很容易,但我没有做太多表单工作,而且我不熟悉它的 DataGridViews 事件。
【问题讨论】:
-
(参见更新示例)
我有一个通过通用列表绑定到的 gridview。我自己设置了所有列。我只是想:
在编辑行时捕获事件 PRE 格式错误 - 通过隐藏字段获取行信息 - 并保持
我相信这一定很容易,但我没有做太多表单工作,而且我不熟悉它的 DataGridViews 事件。
【问题讨论】:
有两种看待这个的方式;
TypeConverter
我通常更喜欢后者,因为它将这种逻辑从 UI 中移除;我看看能不能举个例子……
示例(大部分代码是“显示它工作”的代码);在这里,我定义了一个MyDateTimeConverter,它将日期格式化/解析为它们的向后“dd MMM yyyy”文本(没有很好的理由),并将该转换器与其中一个属性相关联。您可以编辑网格中的值,并将更改推回(更改行以查看“实际”值更新)。由于更改通知的一些细微差别,它不会立即显示;仅仅为此而使示例更复杂是不值得的......
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Forms;
class Person
{
public string Forename { get; set; }
public string Surname { get; set; }
[TypeConverter(typeof(MyDateTimeConverter))]
public DateTime EditableValue { get { return ActualValue; } set { ActualValue = value; } }
// this just proves what we have set...
public DateTime ActualValue { get; private set; }
}
class MyDateTimeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string) || base.CanConvertTo(context, destinationType);
}
const string FORMAT = "dd MMM yyyy";
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value != null && value is string)
{
string s = (string)value;
return DateTime.ParseExact(Reverse(s), FORMAT, CultureInfo.InvariantCulture);
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
return Reverse(((DateTime)value).ToString(FORMAT, CultureInfo.InvariantCulture));
}
return base.ConvertTo(context, culture, value, destinationType);
}
static string Reverse(string value)
{
char[] data = value.ToCharArray();
Array.Reverse(data);
return new string(data);
}
}
class MyForm : Form
{
public MyForm()
{
DataGridView grid = new DataGridView();
grid.Dock = DockStyle.Fill;
List<Person> people = new List<Person>();
people.Add(new Person { Forename = "Fred", Surname = "Flintstone", EditableValue = DateTime.Today });
people.Add(new Person { Forename = "Barney", Surname = "Rubble", EditableValue = DateTime.Today.AddDays(-25) });
grid.DataSource = people;
Controls.Add(grid);
}
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MyForm());
}
}
【讨论】: