Click here to Skip to main content
15,902,732 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a datagridview that has on mouse click event handler where my column "Rate_Per_Day" value = 602.55 and then it will display in my Rate_Per_Day label. In my label it displays as 602.545454545455. How can I display it as a currency and double. Thanks

What I have tried:

<pre>  private void dataGridView2_MouseClick(object sender, MouseEventArgs e)
        {                  
                
                lbl_nameUPDATE.Text = dataGridView2.SelectedRows[0].Cells["Name"].Value.ToString();                    
                txtPosition2.Text = dataGridView2.SelectedRows[0].Cells["Position"].Value.ToString();
                comboBox2.Text = dataGridView2.SelectedRows[0].Cells["Division_Unit_Section"].Value.ToString();
                txtMonthly_Rate2.Text = dataGridView2.SelectedRows[0].Cells["Monthly_Rate"].Value.ToString();
                lbl_RatePerDay.Text = dataGridView2.SelectedRows[0].Cells["Rate_Per_Day"].Value.ToString();
Posted
Updated 26-Jun-18 6:37am

How about:
lbl_RatePerDay.Text = dataGridView2.SelectedRows[0].Cells["Rate_Per_Day"].Value.ToString(".00");
 
Share this answer
 
Comments
RyRen Infinity 25-Jun-18 3:20am    
^ sir error says No over load for method 'Tostrings' take 1 arguments.
[no name] 25-Jun-18 3:40am    
It's ToString(), not Tostrings().
RyRen Infinity 25-Jun-18 3:47am    
oh sorry its a typo :D, anyways, the

lbl_RatePerDay.Text = dataGridView2.SelectedRows[0].Cells["Rate_Per_Day"].Value.ToString(".00");

still says the same error
The Value property returns an object, which doesn't have the standard formatting options.

The quick-and-dirty fix is to use string.Format:
C#
lbl_RatePerDay.Text = string.Format("{0:F2}", dataGridView2.SelectedRows[0].Cells["Rate_Per_Day"].Value);


A more complete fix would be to create your own extension method:
C#
public static class FormattingExtensions
{
    public static string ToString(this object obj, string format, IFormatProvider formatProvider = null)
    {
        if (obj == null) throw new NullReferenceException();
        
        var formattable = obj as IFormattable;
        if (formattable == null) return obj.ToString();
        return formattable.ToString(format, formatProvider);
    }
}
Use:
C#
lbl_RatePerDay.Text = dataGridView2.SelectedRows[0].Cells["Rate_Per_Day"].Value.ToString("F2");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900