Joudicek Jouda
Joudicek Jouda

Reputation: 792

Is it possible to display empty string instead of 0 in DataGridView int columns?

I have a DataTable filled with information about audio tracks. DataTableColumn that stores the track number is of a UInt32 type so when I display the DataTable in DataGridView, I'm able to sort data by that column. For tracks when there is no track number I've got 0 in DataTable.

data.Tables["active"].Columns["Track"].DataType = Type.GetType("System.UInt32");

Is it possible to display every 0 in that column in DataGridView as an empty string (nothing)? But still have it stored as UInt32 0 in DataTable to be able to sort the tracks?

Upvotes: 4

Views: 7753

Answers (3)

PKanold
PKanold

Reputation: 148

An alternate CellFormatting function that displays an empty cell without changing the actual cell value:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "Track")
{
    if (e.Value == 0)
    {
        e.CellStyle.Format = ";;;";
    }
}

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292535

Sure, you can use the CellFormatting event:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "Track")
    {
        uint value = (uint)e.Value;
        if (value == 0)
        {
            e.Value = string.Empty;
            e.FormattingApplied = true;
        }
    }
}

Upvotes: 10

Mohammad abumazen
Mohammad abumazen

Reputation: 1286

just a small suggestion ... add another column with "System.String" and make it's value equal to Track column (hide track column) and then you can replace 0 with empty string in the new visible column

Upvotes: 0

Related Questions