How to show empty gridview when no data is available to display in Asp.Net- C#
In this blog i am going to describe how we could add a custom message in GridView in Asp.Net(c#) in case data is not available in database/ datatable, etc. through code window (Although GridView provides direct property for this when data not available and users could use that property easily but in many case programmer wants to add message through code)
<div>
<asp:GridView ID="TestGrid" runat="server">
</asp:GridView>
</div>
I used a very simple gridview without any styl& design, just to show message when data not available through code window.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillTestGrid();
}
}
protected void FillTestGrid()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("Name", typeof(string));
if (dt.Rows.Count > 0)
{
TestGrid.DataSource = dt;
TestGrid.DataBind();
}
else
{
dt.Rows.Add(contacts.NewRow());
TestGrid.DataSource = dt;
TestGrid.DataBind();
int TotalColumns = TestGrid.Rows[0].Cells.Count;
TestGrid.Rows[0].Cells.Clear();
TestGrid.Rows[0].Cells.Add(new TableCell());
TestGrid.Rows[0].Cells[0].ColumnSpan = TotalColumns;
TestGrid.Rows[0].Cells[0].Text = "<br/>No Record Found</br>";
}
}
In above example i just add added 2 columns : Userid and Name, you may have different columns or you could use database table. It's just for demonstration
- First of all in the design page(.aspx) place a GridView control as:
<div>
<asp:GridView ID="TestGrid" runat="server">
</asp:GridView>
</div>
I used a very simple gridview without any styl& design, just to show message when data not available through code window.
- Now, in the code behind file(.aspx.cs) write the code as ::
protected void Page_Load(object sender, EventArgs e)
{
{
FillTestGrid();
}
}
protected void FillTestGrid()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("Name", typeof(string));
if (dt.Rows.Count > 0)
{
TestGrid.DataSource = dt;
TestGrid.DataBind();
}
else
{
dt.Rows.Add(contacts.NewRow());
TestGrid.DataSource = dt;
TestGrid.DataBind();
int TotalColumns = TestGrid.Rows[0].Cells.Count;
TestGrid.Rows[0].Cells.Clear();
TestGrid.Rows[0].Cells.Add(new TableCell());
TestGrid.Rows[0].Cells[0].ColumnSpan = TotalColumns;
TestGrid.Rows[0].Cells[0].Text = "<br/>No Record Found</br>";
}
}
In above example i just add added 2 columns : Userid and Name, you may have different columns or you could use database table. It's just for demonstration
Comments
Post a Comment