Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

News

My Friends

My Links

Permanent Posts

Portuguese Communities

Displaying Empty GridView

What happens if your GridView control does not have any records to display? Well, if you set the EmptyDataText or EmptyDataTemplate properties, the grid will show something, only probably not what you'd like - the normal structure, as if it was populated with records. Here's a possible solution:


void ShowEmptyRow(GridView grid)
{
	if (grid.Rows.Count == 0)
	{
		DataTable table = new DataTable();

		for (Int32 i = 0; i < grid.Columns.Count; ++i)
		{
			if (grid.Columns [ i ] is BoundField)
			{
				table.Columns.Add((grid.Columns [ i ] as BoundField).DataField);
			}
			else
			{
				table.Columns.Add(grid.Columns [ i ].SortExpression);
			}
		}

		table.Rows.Add(table.NewRow());

		grid.DataSourceID = String.Empty;
		grid.DataSource = table;
		grid.DataBind();

		if (String.IsNullOrEmpty(grid.EmptyDataText) == false)
		{
			grid.Rows [ 0 ].Cells [ 0 ].ColumnSpan = table.Columns.Count;
			grid.Rows [ 0 ].Cells [ 0 ].Text = grid.EmptyDataText;

			while (grid.Rows [ 0 ].Cells.Count > 1)
			{
				grid.Rows [ 0 ].Cells.RemoveAt(1);
			}
		}
	}
}

Bookmark and Share
Posted: Jun 25 2010, 11:39 AM by Ricardo Peres | with 3 comment(s)
Filed under: ,

Comments

habdulrauf said:

Very nice solution to a common problem, Thanks

# June 26, 2010 12:39 AM

Twitter Trackbacks for Displaying Empty GridView - Development With A Dot [asp.net] on Topsy.com said:

Pingback from  Twitter Trackbacks for                 Displaying Empty GridView - Development With A Dot         [asp.net]        on Topsy.com

# June 26, 2010 10:12 AM

Waheed Ahmad said:

Very nice code. which i requred. thanks alot

# March 27, 2012 3:42 AM