Alex Rivera | Logout

How to custom format data in datagridview during databinding

Asked 2010-01-22T12:40:33.973
15

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
Edit
Report

2 Answers

5

Add a property to your class that does the substringing for you, and bind to that.

answered 2010-01-22T12:43:22.760
-1

You could always call a custom format function like so from your aspx page:

<asp:GridView ID="gvPlatforms" runat="server" AutoGenerateColumns="false"
          GridLines="None">
<Columns>
    <asp:TemplateField HeaderText="Icon">
        <ItemTemplate>
            <asp:Image ID="imgPlatformLogo" runat="server" ImageUrl='<%#GetImagePath(Eval("Abbr")) %>' />
        </ItemTemplate>
    </asp:TemplateField>
</Columns>

And then in your code behind for that page:

protected string GetImagePath(object abbr){
return string.Format("{0}{1}.gif", Constants.URLs.PLATFORM_LOGOS, abbr.ToString());}
answered 2010-01-22T14:11:39.963

Your Answer