Cla*_*ack 15 c# data-binding format datagridview winforms
我正在寻找一种格式化DataGridViewTextBoxColumn的方法,以便在数据绑定期间格式化数据表的值.例如,我有一个CompanyName属性,当数据绑定发生时,我需要从CompanyName获取前5个字母.
我可以挂钩不同的DataGridView事件(例如RowsAdded)并遍历所有行并执行操作,但我想找到更复杂的方法来执行此操作.由于我已决定使用数据绑定,因此循环数据并对其进行修改有点违背了数据绑定概念.
我所追求的是,如何做到如下,但添加自定义格式逻辑:
dataGridView1.Columns[colSomeDate.Index].DataPropertyName = "SomeDate";
colSomeDate.DefaultCellStyle.Format = "yyyy";
Run Code Online (Sandbox Code Playgroud)
我想我应该实现IFormatProvider,但我不太明白我应该如何实现它.
dataGridView1.Columns[companyName.Index].DataPropertyName = "CompanyName";
companyName.DefaultCellStyle.FormatProvider = new ShortText(); // ShortText should implement IFormatProvider
Run Code Online (Sandbox Code Playgroud)
Tro*_*ond 21
我不知道IFormatProvider,但DataGridViews CellFormatting事件可以帮助你吗?
private void dataGridView1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 0)
{
e.Value = e.Value.ToString().Substring(0, 5); // apply formating here
e.FormattingApplied = true;
}
}
Run Code Online (Sandbox Code Playgroud)
http://msdn.microsoft.com/en-us/library/z1cc356h.aspx?ppud=4
向您的类添加一个属性,为您执行子串,并绑定到该属性.
这是我为了让我的工作而做的
public class MyFormatProvider : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
// Check whether this is an appropriate callback
if (!this.Equals(formatProvider))
return null;
//if argument/ value is null we return empty string
if (arg == null)
return null;
string resultString = arg.ToString();
//transform resultString any way you want (could do operations based on given format parameter)
//return the resultant string
return resultString;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我然后放入我的单元格格式处理程序
//In your datagridview, handle the cell formatting event in required cell as
if (e.ColumnIndex == dgvPayments.Columns["amount"].Index)
{
e.Value = String.Format(new MyFormatProvider (), "{0:U}", e.Value);
e.FormattingApplied = true;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36337 次 |
| 最近记录: |