Change culture of DataGridView programmatically?

I would like to change the pricing column in my DataGridView based on the currency selected by the user in the ComboBox currency.

The price column is currently formatted to "C2". This default looks like "$ 1.00".

However, if my user were to switch the currency to Great British Pound, I would like to display the Great British Pound (“ÂŖ”) sign, not the dollar sign (“$”), so the end result is ÂŖ 1.00.

Any suggestions on how to change the culture of the DataGridView?

Thanks in advance!

0


source to share


1 answer


You are looking for System.Globalization . There is a BUNCH of various options ...

If you just want to change it for that specific element:

   //Label example but theory is the same
    [CultureInfo][2] ci = new CultureInfo("en-GB");
    double myMoney = 100.00;
    this.Label1.Text = myMoney.ToString("C2", ci);

      

If you want to change it for everything, you can

     //Will format everything
     string strCulture = "en-GB";//Session["culture"].ToString();
     [CultureInfo][3] ci = new CultureInfo(strCulture);
     Thread.CurrentThread.[CurrentCulture][4] = ci ;
     Thread.CurrentThread.[CurrentUICulture][5] = ci;
     double myMoney = 100.00;
     this.Label1.Text = myMoney.ToString("C2");

      

In DataGird, if you are trying to format a data string, you need to hook into the onDataBound event and reformat that path, as I don't believe you can pass an argument like: DataFormatString = "{0: c, en-GB}

Something like this should do the trick (not tested)



  protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //Define CultureInfo in page scope just put in example for reference
        [CultureInfo][6] ci = new CultureInfo("en-GB");
        if (e.Row.RowType == DataControlRowType.DataRow)
            ((Label)e.Row.FindControl("myMoney")).Text.ToString("C2", ci);
   }

      

OR

If you are binding to DataTable you can explicitly set DataTable Cultureinfo

CultureInfo ci = new CultureInfo("en-GB");
myTable.Locale = ci;

      

If you are looking for extensive cultural support for the system (which I don't think you should, but worth mentioning), you can look at the resource files

Simple example :

ResourceManager rm = ResourceManager.CreateFileBasedResourceManager("resource", "path to resouce files", null);
this.Label1.Text = rm.GetString("name");

      

+1


source







All Articles