Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

c# - How to custom format data in datagridview during databinding

I'm looking for a way to format DataGridViewTextBoxColumn so that the value to be databinded is formatted during databinding. For example I have a CompanyName property and I need to take first 5 letters from the CompanyName when databinding happens.

I could hook on different DataGridView events (e.g. RowsAdded) and loop through all the rows and do the trick, but I'd like to find more sophisticated way to do this. Since I have decided to use databinding, looping through data and modifying it is a bit against the databinding concept.

What I'm after, is how to do the same as below, but add custom formatting logic:

dataGridView1.Columns[colSomeDate.Index].DataPropertyName = "SomeDate";
colSomeDate.DefaultCellStyle.Format = "yyyy";

I think I should implement IFormatProvider, but I don't quite understand how I should implement it.

dataGridView1.Columns[companyName.Index].DataPropertyName = "CompanyName";
companyName.DefaultCellStyle.FormatProvider = new ShortText(); // ShortText should implement IFormatProvider
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't know about the IFormatProvider, but can the DataGridViews CellFormatting-event help you?

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;
    }
}

http://msdn.microsoft.com/en-us/library/z1cc356h.aspx?ppud=4


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...