How to format data in the Data Grid
Question and answer on the DataGrid, Datasets.How do you format the information, and trap user interaction.Question:
I have a question, do you happen to know how to format data as it is going into a datagrid from adataset and dataadapter? I want to format my numbers in one for one field with four decimal places and then the next field with two decimal places and another with 3 digits total and no decimal places. I cannot control the data that user is putting in, but the data that is displayed in the application should be easier. Any ideas?
It isf or Win forms, if it were web forms I would be all set, because the Help that comes with Visual Studio provides an example. I actually need to format entire columns of data.
I do not know if you know the answer to this question, but is there a way for me to check data as it goes into each cell in a datagrid? As I see it, the data adapter fills with data depending on the query, then this data fills the data set. I want to make sure that there is only numeric data and that it is formatted correctly. I have been knocking myself out trying to nest SQL statements for the data adapter for the formatting and I cannot figure it out, but checking each cell's data is a different matter. Any help is appreciated.
Answer:
Formatting data in the DataGrid is quite simple. You can do it in the designer, or in code. This figure shows how it's done in the designer. The "Format" property of the DataGridTextBoxColumn is a standard .NET string format specifier. In the attached JPG, I've set the format for the Price column to N4, which displays 4 decimal places. All the format specifiers you need are in this MSDN page.This is one of my gripes with VS.NET in the current version. If you are using the default mechanism of displaying *all* columns, you need to create every column by hand in the designer.
Or, you can write code to find the column, and change the specifier that way, in your form's load handler.
DataGridTableStyle style = dataGridTitles.TableStyles["titles"];
DataGridTextBoxColumn columnStyle = style.GridColumnStyles["Price"] as DataGridTextBoxColumn;
columnStyle.Format = "N2";
Verifying the data requires subscribing to the DataColumnChangeEvent in the dataset. This event gives you both the current & proposed values for the column. You can allow or cancel any change.