In this article, we are going to learn inserting a Empty Row into gridview control when GridView doesn't have record.
In designer file:
In Designer File, create a GridView control. Add three Label control in ItemTemplate for Id, EmpName, EmpAddress columns.
div align="center">
GridView ID="grdEmployee" runat="server" AutoGenerateColumns="False"
AllowPaging="true" ShowFooter="true" PageSize="5" BorderColor="SkyBlue">
HeaderStyle BackColor="#00A6DC" ForeColor="White" />
TemplateField HeaderText="Employee Id">
Label ID="lblId" runat="server" Text=''>
Label>
TemplateField>
TemplateField HeaderText="Employee Name">
Label ID="lblEmpName" runat="server" Text=''>
Label>
TemplateField>
TemplateField HeaderText="Employee Address">
Label ID="lblEmpAddress" runat="server" Text=''>
Label>
TemplateField>
GridView>
div>
Namespaces used
Include the below Namespace.
using System.Data;
Complete Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
DataSet ds = GetData();
if (ds.Tables[0].Rows.Count > 0)
{
grdEmployee.DataSource = ds;
grdEmployee.DataBind();
}
else
{ //adding Empty row
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
grdEmployee.DataSource = ds;
grdEmployee.DataBind();
grdEmployee.Rows[0].Visible = false;
}
}
//method returning zero record
private DataSet GetData()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(Int32));
dt.Columns.Add("EmpName", typeof(string));
dt.Columns.Add("EmpAddress", typeof(string));
ds.Tables.Add(dt);
return ds;
}
Explanation:
When page loads, BindGrid() method will get called which will Add Empty Row to Gridview. GetData method will return zero record. Below is code to add blank row to DataSet.
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
grdEmployee.DataSource = ds;
grdEmployee.DataBind();
grdEmployee.Rows[0].Visible = false;
}
Output:
Output will be shown as below.