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.
C D 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

 

 

 

C D 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>
help
the following code not displaying data in gridview. . . gridview is inside the Form1;; it displaying empty column with 3rows List <int > ls = new List 4 ); ls.Add( 5 ); dataGridView1.DataSource = ls; what is the problem. . .? add this line GridView1.DataBind(); no. . .there is no such a method. . . ok. . for windows app private void button1_Click( object ls.Add(3); ls.Add(4); ls.Add(5); dataGridView1.ColumnCount = 1; / / Adding column with header name dataGridView1.Columns[0].Name = "Name" ; for ( int i = 0; i < 3; i++) { dataGridView1.Rows.Add(ls[i].ToString()); } } keywords: EventArgs, DataBind, new List, Click, gridview description: gridview the following code not displaying data in gridview. . . gridview is inside the Form1;; it displaying
If thre is no record in my gridview, page doesn't anything.What i want is to display atleast header of gridview. Plz help me. Here is generic function which i use to fix empty gridview: U can call this function right after binding grid. e.g. GridView1.DataSource = objDataSource; GridView1.Bind(); EmptyGridFix( GridView1); . . . if ur grid is empty it will display only header of it. #region- -Empty Grid Fix- - protected void EmptyGridFix(GridView grdView) { / / normally executes after a grid load method if (grdView.Rows.Count = = 0 && grdView.DataSource
Hi friends i am developing a web Update Panel> <Panel> <Timer> < / Timer<Gridview1> < / Gridview1> > < / Panel> < / Update Panel> i want to freeze the gridview header and the gridview autogenerate column is true. How to freeze gridview header please help me Thanks chandan protected void Freeze Gridview Header ( GridView _gv1, Table _tb1, Panel _pc1) { Page.EnableViewState = false ; / / [Español]Copiando las propiedades del
i have a gridview.i want to align gridview header vertically.then add textbox item template to each.can we aling gridview header vertically. . . . . . . . . . The below code is used to display the gridview header vertically. Or else you can dispaly one cell of gridview header text vertically. < asp:GridView
Hi All, I have a gridview with 5 columns. When i click on header column i would like to change the entire header column background color (something like highlighting the header column, so that one can distinguish from rest of the column or changing header column cell background color) Please advice me. . Regards Lokesh public class DynamicHeaderCell { public String Header { get ; set ; } public int RowSpan { get ; set ; } public int ColSpan { get ; set ; } public DynamicHeaderCell( String
I have a gridview with column headers. These differ slightly from the underlying table. Example is the table has ChangeRequestStatus while gridview has Status. On a label below the gridview I have what is being sorted. Rather then the table I would prefer to have the gridview column header. The line below provides what the underlying datatable has. lblSortColumn.Text = "Sorted by: " + e.SortExpression; I am not getting what would be used to show the gridview column header. Any assistance in this is welcomed. Thanks. John ASP.NET Discussions GridViewSortEventArgs (1
Dear All, I have created a multi row header in grid view at row data bound So when there is no data it does not show the multi row header.But i want it to show like other grids like if there is no data header should come. Please help.Its very urgent. If i am not clear please ask. Thanks advance April June HI Check the below example Here’s the method for showing the Header and Footer of GridView when no data returned in the query. private void ShowNoResultFound( DataTable source, GridView gv) { source.Rows.Add(source.NewRow()); / / create a new blank row to the DataTable / / Bind
make scrollable gridview in which header fixed with verticly header move with horizontal scrollbar please help me now try this code < style type = "text / css style > hi thanks for reply, i have the following code in wich i use a gridview and table for header data in gridview move in both direction but as i scroll horizontal the header not move with scrol
Hi every body I have some problems in fixing Gridview Header and Footer when I scroll. Pls help me and tell me also on which Internet server"> <div> <asp:Panel ID = "gridPanel" runat = "server" Height = "200px" Width = "700px" ScrollBars = "Auto"> <asp:GridView ID = "GrvMfdetails" runat = "server" ShowFooter = "true" AutoGenerateColumns = "false" OnRowCommand = "GrvMfdetails_RowCommand" OnRowDataBound = "GrvMfdetails_RowDataBound" OnSelectedIndexChanged = "GrvMfdetails_SelectedIndexChanged"> <Columns AntiqueWhite" BorderColor = "#CC3300" BorderStyle = "Double" BorderWidth = "3px" Font-Bold = "True" Font-Size = "Larger"> < / FooterStyle> < / asp:GridView> < / asp:Panel> < / div> < / form> < / body> < / html> Hello Bhau, use this sample . http: / / www.codeproject.com parentNode.parentNode.scrollLeft); } it will work with all the browsers Regards D you can fixed header and footer of gridview when scrolling it by using CSS class and javascript as follows in CSS .GV Fixed