How to custom format data in datagridview during databinding

前端 未结 7 770
忘掉有多难
忘掉有多难 2020-12-16 14:21

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

7条回答
  •  执笔经年
    2020-12-16 15:01

    Here is what I did to get mine to work

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

    This is what i then put in my cell formatting handler

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

提交回复
热议问题