Windows Develop Bookmark and Share   
 index > Windows Forms Data Controls and Databinding > How to format a datagridview column
 

How to format a datagridview column

I am using the following:

Code Snippet

private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)

{

string.Format("{0:D2}", e.Value);

}

However when I have a value of 150.30 is shows as 150.3

How would I formatthe column so that 150.30 shows.

Can-Ann  Tuesday, June 26, 2007 4:30 PM

Code Snippet

dgvMain.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = String.Format("{0:#.00}", (double)e.Value);

element109  Tuesday, June 26, 2007 8:27 PM

Hi, Can-Ann,

I wrote a small sample to show how to control the Format of a cell

Code Snippet

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("abc");
dt.Columns.Add("bcd",typeof(float));
dt.Rows.Add("aaa", 120.0);
dt.Rows.Add("bbb", 128.10);


dataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);

dataGridView1.DataSource = dt;
}

void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 1)
{
e.Value = string.Format("{0:F2}", e.Value);
}
}

Hope this helps

Regards,

Yu Guo â€?MSFT  Thursday, June 28, 2007 4:32 AM

Code Snippet

dgvMain.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = String.Format("{0:#.00}", (double)e.Value);

element109  Tuesday, June 26, 2007 8:27 PM

Hi, Can-Ann,

I wrote a small sample to show how to control the Format of a cell

Code Snippet

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("abc");
dt.Columns.Add("bcd",typeof(float));
dt.Rows.Add("aaa", 120.0);
dt.Rows.Add("bbb", 128.10);


dataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);

dataGridView1.DataSource = dt;
}

void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 1)
{
e.Value = string.Format("{0:F2}", e.Value);
}
}

Hope this helps

Regards,

Yu Guo â€?MSFT  Thursday, June 28, 2007 4:32 AM

You can use google to search for other answers

Custom Search

More Threads

• Updating mulitple tables on the same form
• CheckedListbox and Hashtable
• updating an ID
• Inject Querystring on server side
• Is "simple data binding" in v1.1 one-way by default?
• picture images
• Increase spacing between items in ListView
• System.IndexOutofRangeException ... Index {{X}} does not have a value...
• Clear BindingSource bounded with dgv and how to decide whether the dataTable exists in the dataSet.
• BindingList<T> - not throwing ListChanged event