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
504 views
in Technique[技术] by (71.8m points)

c# - DataGridView - how to set the currency format for a single column ONLY

I am trying to use the datagridview for a basket. I have got it to display the basket of the customer but I would like it to display the currency for the Price column, but i have a Quantity column as well, so if I put the default style as currency then it will change both columns to the currency format.

What I want to be able to do is add the currency format to the Price Column but not to the quantity column.

Here is the code that displays the basket (Form_load)

using (var con = new SqlConnection(connectionString))
        {
            SqlDataAdapter dataadapter =
          new SqlDataAdapter(
              "select p.productname 'Product Name', b.productquantity 'Quantity', c.categoryname 'Category', p.price 'Current Price' " +
              "from basket b join products p on b.productid = p.productid " +
              "join Categories c on c.categoryid = p.categoryid " +
              $"where b.customerid = {CustomerId}", con);

            DataSet ds = new DataSet();
            con.Open();
            dataadapter.Fill(ds);
            con.Close();
            dataGridView1.DataSource = ds.Tables[0].DefaultView;
        }

The CustomerId is collected from a txt file that stores the CustomerId when they log in.

If there is any more code that you would like to see then comment and i will add it.

This is what i get on the form with the currency added as the style. enter image description here

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can set format of data of a column using Format property of its DefaultCellStyle property of the column.

For example to use currency format for second column of a DataGridView using current culture, you can use such code:

grid1.Columns[1].DefaultCellStyle.Format = "c";

Or for example to use an specific culture and specific decimal numbers:

grid1.Columns[1].DefaultCellStyle.Format = "c2";
grid1.Columns[1].DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo("en-GB");

More Information

Note

If you are using an object data source, then you can use the following approaches as well. The Foundation is same, setting suitable format for the column, but using attributes:


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

...