In using gridview it always show data when in table have data.
if in table not have data when you use it, not show anything in
gridview. but we can show header by nothing data in table.
If you want to know and want to use it please see code and
practice it as below:
/// Show grid even if datasource is empty
protected void EmptyGridFix(GridView grdView)
{
// normally executes after a grid load method
if (grdView.Rows.Count == 0 &&
grdView.DataSource != null)
{
DataTable dt = null;
// need to clone sources otherwise it will be indirectly adding to
// the original source
if (grdView.DataSource is DataSet)
{
dt = ((DataSet)grdView.DataSource).Tables[0].Clone();
}
else if (grdView.DataSource is DataTable)
{
dt = ((DataTable)grdView.DataSource).Clone();
}
if (dt == null)
{
return;
}
dt.Rows.Add(dt.NewRow()); // add empty row
grdView.DataSource = dt;
grdView.DataBind();
// hide row
grdView.Rows[0].Visible = false;
grdView.Rows[0].Controls.Clear();
}
// normally executes at all postbacks
if (grdView.Rows.Count == 1 &&
grdView.DataSource == null)
{
bool bIsGridEmpty = true;
// check first row that all cells empty
for (int i = 0; i < grdView.Rows[0].Cells.Count; i++)
{
if (grdView.Rows[0].Cells[i].Text != string.Empty)
{
bIsGridEmpty = false;
}
}
// hide row
if (bIsGridEmpty)
{
grdView.Rows[0].Visible = false;
grdView.Rows[0].Controls.Clear();
}
}
}
/// This code below for select data form table. write it in page load in page
protected void LoadGrid()
{
DataSet dsMyDataSet = new Dataset();
SqlDataAdapter Dadapter=new SqlDataAdapter _
("Select * From TableName",Connection);
Dadapter.Fill(dsMyDataSet);
// obtain dataset/datatable from DAL/BAL
grdYourGrid.DataSource = dsMyDataSet.Table[0];
grdYourGrid.DataBind();
this.EmptyGridFix(grdYourGrid);
}
No comments:
Post a Comment