Sunday, August 31, 2014

Populate asp.net gridview when data is empty

Asp.net that doesn't provide to display grid-view in empty. :)
Let’s explain it in example
//dt=DataTable which is empty .
Gridview1.DataSource=dt;
GridView1.DataBind();
Above mentioned code, that will not displayed gridview, because of it is empty.to overcome to this issue we can use  EmptyDataText="Data Not Found" propery in gridview.
it's better than displaying invisible gridview to user.



another option (much user friendly)
Binding user define datatable with one datarow.
 DataTable dt = new DataTable();
dt.Columns.Add("Name");
 dt.Columns.Add("ID");                                                   
 DataRow dr;
dr = dt.NewRow();
dr["Name"] = "xx";
dr["ID"] = "xx";
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();

more efficient way
ShowHeaderWhenEmpty="true" property in gridview set to true.
and set the emptydataTemplate
            <EmptyDataTemplate>
                Data Not Found
            </EmptyDataTemplate>
advantage : no need work with the datatable to display empty row.

happy coding Download

No comments:

Post a Comment