ASP.NET - Gridview Header display when datasource=null

Asked By Krishna T on 29-Jun-12 09:57 AM
Earn up to 10 extra points for answering this tough question.
Hi,

MilestoneDetailsList = objBal.MilestoneDetails(ProjectName);
          gvMileStones.DataSource = MilestoneDetailsList;
         if (MilestoneDetailsList != null)
          {
            gvMileStones.DataBind();
            clearData();
          }
          else {
            gvMileStones.DataBind();
            clearData();            
            lblResult.Text = "No Records Found!";
         }         
 The Above code didn't showing headers in gridview when no records found.  I need display gridview headers when datasource==null
Super Man replied to Krishna T on 29-Jun-12 12:59 PM

In .aspx Page:

 

     Set ShowHeaderWhenEmpty="true" property of Gridview

 

 

   <asp:GridView ID="GridView1" runat="server" ShowHeaderWhenEmpty="true" >


In .aspx.cs Page

          If MilestoneDetailsList is not null then assign it to datasource of Gridview and if the datasource null , then create one instance of it (blank instance , contains no data)

So it will display the columnNames.


      XYZ_Type_of_MilestoneDetailsList MilestoneDetailsList = null;

 

      MilestoneDetailsList = objBal.MilestoneDetails(ProjectName);

      if (MilestoneDetailsList != null)

      {

        gvMileStones.DataSource = MilestoneDetailsList;

        gvMileStones.DataBind();

        clearData();

      }

      else

      {

        gvMileStones.DataSource = new XYZ_Type_of_MilestoneDetailsList();

        gvMileStones.DataBind();

        clearData();

        lblResult.Text = "No Records Found!";

      }  






kalpana aparnathi replied to Krishna T on 29-Jun-12 02:40 PM
hi,

Try below code:

if(dt.Rows.Count > 0 )
 {
        //DataSource is not empty
        gvResults.DataSource = dt;
        gvResults.DataBind();
   }
  else
  {
        //DataSource empty, add dummy row
        dt.Rows.Add(dt.NewRow());
        gvResults.DataSource = dt;
        gvResults.DataBind();
       //Make dummy row invisible
        gvResults.Rows[0].Visible = false;
   }


Regards,
Ravi Maurya replied to Krishna T on 30-Jun-12 02:36 AM
Alternative is to display simple table when no record found by query do refer this link

http://www.aspsnippets.com/Articles/Show-Header-when-GridView-is-Empty.aspx 

Hope it might help you.
Chintan Vaghela replied to Krishna T on 30-Jun-12 03:10 AM

Hi Frndz,

 

Functionality:  Show Header When there is not Records in GridView

 

 

To achieve this task,

 

Need to check DataTable Value is 0 or not.

 

If datatable value is 0 then added one blank row

 

            if (dt.Rows.Count == 0)

            {

              dt.Rows.Add(new object[] { "No Records" });

 

            }

After check data table value Bind Grid with DataTable

 

            gvBlockDetail.DataSource = dt;

            gvBlockDetail.DataBind();

 

Check Below logic for more deatil

 

 

Full Logic     :

 

 

string Constr = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;

        using (SqlConnection con = new SqlConnection(Constr))

        {

          using (SqlCommand cmd = new SqlCommand("select BlockCode,BlockName from M_Block where BlockName='aa'", con))

          {

            con.Open();

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            DataTable dt = new DataTable();

            da.Fill(dt);

            if (dt.Rows.Count == 0)

            {

              dt.Rows.Add(new object[] { "No Records"});

 

            }

            gvBlockDetail.DataSource = dt;

            gvBlockDetail.DataBind();

          }

        }

 

 

Hope this helpful!

Thanks

 

 

 

Chintan Vaghela replied to Krishna T on 30-Jun-12 03:50 AM

Hi Frndz,

 

Functionality:  Merge All columns with Message when no records in Gridview

 

 

To achieve this task,

 

 

Firs check DataTable value as above post.

 

 

After then  check message  condtion

if (dt.Rows[0][0].ToString() == "No Record(s) Found")

{

 

 

}

 

After then using ColumnSpan Property, merge all Cell value into single cell

 

gvBlockDetail.Rows[0].Cells[0].ColumnSpan = 3

 

After then remove other cell

 

 

gvBlockDetail.Rows[0].Cells.RemoveAt(i);

 

 

Check Below logic for more detail

 

 

Full Logic     :

 

 

DataTable dt = new DataTable();

da.Fill(dt);

if (dt.Rows.Count == 0)

{

    dt.Rows.Add(new object[] { "No Record(s) Found" });

}

gvBlockDetail.DataSource = dt;

gvBlockDetail.DataBind();

if (dt.Rows[0][0].ToString() == "No Record(s) Found")

{

    int cellCount = gvBlockDetail.Rows[0].Cells.Count;

    gvBlockDetail.Rows[0].Cells[0].ColumnSpan = cellCount;

    for (int i = cellCount - 1; i > 0; i--)

    {

      gvBlockDetail.Rows[0].Cells.RemoveAt(i);

    }

}

 

Hope this helpful!

Thanks

 

 

 

Vikram Singh Saini replied to Krishna T on 30-Jun-12 03:51 AM
By looking your code and requirements, I can suggest you to use alternative solution for same. Might be it could be best for your problem.

Use EmptyDataTemplate in GridView. It would get display to user whenever there is no row in gridview. Here is code:

<asp:GridView ID="gvUploadedFiles" runat="server" CssClass="grid" AutoGenerateColumns="false" Width="100%" DataSourceID="adsUploadedFiles">     

      <EmptyDataRowStyle CssClass="empty" />

      <Columns>

        <asp:BoundField HeaderText="Format" DataField="Format" Visible="false" />

        <asp:TemplateField HeaderText="Format">

          <ItemTemplate>

            <asp:Image ID="imgFormat" runat="server" /></ItemTemplate>

        </asp:TemplateField>

      </Columns>

      <EmptyDataTemplate>

        No records found…

      </EmptyDataTemplate>     

    </asp:GridView>


bharti odedra replied to Krishna T on 30-Jun-12 08:29 AM
try this code

string Cstr = ConfigurationManager.ConnectionStrings["MyCon"].ConnectionString;

      using (SqlConnection c1 = new SqlConnection(Cstr))

      {

      using (SqlCommand cd1 = new SqlCommand("select BlockCode,BlockName from M_Block where BlockName='aa'", c1))

      {

        c1.Open();

        SqlDataAdapter d1 = new SqlDataAdapter(cd1);

        DataTable t1 = new DataTable();

        d1.Fill(t1);

        if (dt.Rows.Count == 0)

        {

        t1.Rows.Add(new object[] { "No Records"});

 

        }

        gvBlockDetail.DataSource = t1;

        gvBlockDetail.DataBind();

      }

      }

[)ia6l0 iii replied to Krishna T on 01-Jul-12 09:40 AM
Almost all sample code above hide the header for you. They do not seem to show you, the header when there is no data. 

This is what you need. 

a) Your database query should return a empty dataset, but with the column headers. For e.g. in your code,  the following two lines should ensure that the MilestoneDetailsList returns a empty datatable (with no rows, but with column headers)
MilestoneDetailsList = objBal.MilestoneDetails(ProjectName);
gvMileStones.DataSource = MilestoneDetailsList; 

b) If the above step is ensured to work, then all you need to do is bind the data. The bool property that folks suggest above is not required too. This is most often required, when you would override and write your own data like "No records were retrieved for the condition...."

Hope this clears the air.


S K replied to Krishna T on 02-Jul-12 03:23 AM
You can achive such goal using two way one is either use inbuilt Emptyrowdata property of gridview and other is can bind empty datatable when bindg datasourec id row are zero
see the sample code here
http://www.aspdotnet-suresh.com/2010/12/v-behaviorurldefaultvmlo.html 
Krishna T replied to [)ia6l0 iii on 02-Jul-12 08:31 AM
I am using Dataset But still not able to show Headers in Grid view Please verify my previous post and send me suitable answer.
s j replied to Krishna T on 27-Sep-12 07:40 AM
Logic is , if you don't have data in grid then simply create one data table with columns and display it like i did in my code. 

If dt.Rows.Count > 0 Then
                    FormatMoneyDataTable(dt, "LoanAmount")
                    GridBids.DataSource = dt
                    GridBids.DataBind()
                Else
                    'This is to Show Grid header only if no bids 
                    Dim dt1 As New DataTable
                    dt1.Columns.Add("BidID")
                    dt1.Columns.Add("AcceptedBidID")
                    dt1.Columns.Add("Borrower")
                    dt1.Columns.Add("LoanAmount")
                    dt1.Columns.Add("AcceptedDate")
                    dt1.Columns.Add("CurrentStatus")
                    dt1.Columns.Add("LastUpdatedDate")
                    dt1.Rows.Add(dt1.NewRow())
                    GridBids.DataSource = dt1
                    GridBids.DataBind()
                    GridBids.Rows(0).Visible = False
                    lblMsg.Visible = True
                End If
            End If
            Dim y, z As Integer


            For y = 0 To GridBids.Rows.Count - 1
                For z = 0 To GridBids.Columns.Count - 1
                    GridBids.Rows(y).Cells(z).Style.Add("padding-left", "0px !important")
                Next
            Next

Try this and let me know. 



aneesa replied to Krishna T on 01-Oct-12 01:36 AM
<%--USE EmptyDataTemplate after   <Columns>...</Columns> in gridview LIKE BELOW--%>
 
 <EmptyDataTemplate>
  <asp:Label ID="Label12" runat="server" Text="No Records Exists" ForeColor="Red"></asp:Label>
 </EmptyDataTemplate>