Friday, December 16, 2011

Show Header of GridView when it has no rows to show

------------------
.aspx file
------------------
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Grdview with Header</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
width:300px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvdata" runat="server" CssClass="Gridview" AutoGenerateColumns="false" HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="White">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID"/>
<asp:BoundField DataField ="name" HeaderText="Name" />
<asp:BoundField DataField="Sal" HeaderText="Salary" />

</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
----------------------------
.cs file
----------------------------
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGridviewData();
}
}
protected void BindGridviewData()
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=testdb;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select id,name,sal from emp ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if(ds.Tables[0].Rows.Count==0)
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvdata.DataSource = ds;
gvdata.DataBind();
int columncount = gvdata.Rows[0].Cells.Count;
gvdata.Rows[0].Cells.Clear();
gvdata.Rows[0].Cells.Add(new TableCell());
gvdata.Rows[0].Cells[0].ColumnSpan = columncount;
gvdata.Rows[0].Cells[0].Text = "No Records Found";
}
else
{
gvdata.DataSource = ds;
gvdata.DataBind();  
}
con.Close();
}
 

No comments:

Post a Comment