我有一个通过泛型列表绑定到的网格视图。所有的栏目都是我自己设置的。我只是想:
在编辑行时捕获事件预格式错误-通过隐藏字段获取行信息-并持久保存
我相信这一定很简单,但是我没有做过太多的表单工作,我也不熟悉它的DataGridViews事件。
发布于 2009-03-11 14:17:26
有两种方式来看待这一点;
上使用自定义TypeConverter
我通常更喜欢后者,因为它从UI中去掉了这个逻辑;我会看看我是否可以做一个例子……
例如(这段代码的大部分代码是"show it with“代码);在这里我定义了一个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());
}
}https://stackoverflow.com/questions/634643
复制相似问题