Basically I have a gridview with 2 columns (id, years). When there is no data for the source of this gridview, I want to show header and footer rows and inside the gridview, a message will be displayed to the user (NO RECORDS FOUND).
I have already tried using gridview properties ShowHeaderWhenEmpty="true"
and EmptyDataText="no records found"
. This method does show the message but as gridview is empty so it won't show the footer row.
Here is result:
Then I read somewhere that I should add an empty dummy row to gridview when gridview is empty and I also tried that, now it does show header and footer and also show the message but one small problem is that the message is shown only in first column if gridview and others columns are shown empty
Here is code behind used for above image
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
public void BindGridview()
{
//if datatable has rows meaning data source is not empty
if(((DataTable)this.Get_Details()).Rows.Count > 0)
{
GridView1.DataSource = this.Get_Details();
GridView1.DataBind();
}
else
{
//if the Data is empty then bind the GridView with an Empty Dataset
GridView1.DataSource = this.Get_EmptyDataTable();
GridView1.DataBind();
}
}
public DataTable Get_Details()
{
DataTable dt = new DataTable();
string cs = WebConfigurationManager.ConnectionStrings["USTB-OBE-DATABASE"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
string query = "select * from test3";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
con.Open();
cmd.ExecuteNonQuery();
dt = ds.Tables[0];
}
return dt;
}
public DataTable Get_EmptyDataTable()
{
DataTable datatableEmpty = new DataTable();
//Here ensure that you have added all the column available in your gridview
datatableEmpty.Columns.Add("id", typeof(string));
datatableEmpty.Columns.Add("year", typeof(int));
DataRow dataRow = datatableEmpty.NewRow();
//Inserting a new row,datatable .newrow creates a blank row
dataRow[0] = "no records found";
datatableEmpty.Rows.Add(dataRow);//adding row to the datatable
return datatableEmpty;
}
}
But I actually want that both columns are col-spanned and whole row is shown as single column and message is displayed inside meaning that I want this enter image description here result but i also want the footer to be displayed also.
I would really appreciate if anyone could help.