I have ASP.Net GridView with 5 TextBoxes in every row. Page size of GridView is 20 records on each page.
I have enabled sorting on every column. When GridView is getting populated, then we are getting 28 filled records and 12 empty records.
When I hit sorting in asc mode on any column, it gives blank rows earlier then records are coming. I wanted to ignore those blank records while sorting.
I tried using custom onsorting method on GridView but it’s not working.
<asp:GridView runat="server" ID="gvDetails" AllowPaging="true" PageSize="20" Allow AutoGenerateColumns="false"
DataKeyNames="ProdId" OnPageIndexChanging="gvDetails_PageIndexChanging" OnSorting="gvDetails_OnSorting">
<HeaderStyle CssClass="headerstyle" />
<Columns>
<asp:TemplateField SortExpression="ProdName">
<ItemTemplate>
<asp:TextBox ID="txtProductName" runat="server" Text='<%# Eval("ProdName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField SortExpression="ProdDesc">
<ItemTemplate>
<asp:TextBox ID="txtProdDesc" runat="server" Text='<%# Eval("ProdDesc") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField SortExpression="ProdPrice">
<ItemTemplate>
<asp:TextBox ID="txtProdPrice" runat="server" Text='<%# Eval("ProdPrice") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField SortExpression="ProdCat">
<ItemTemplate>
<asp:TextBox ID="txtProdCat" runat="server" Text='<%# Eval("ProdCat") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
protected DataTable BindGridview()
{
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection("#"))
{
con.Open();
SqlCommand cmd = new SqlCommand("crudoperations", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@status", "SELECT");
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvDetails.DataSource = ds;
gvDetails.DataBind();
int columncount = gvDetails.Rows[0].Cells.Count;
gvDetails.Rows[0].Cells.Clear();
gvDetails.Rows[0].Cells.Add(new TableCell());
gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
gvDetails.Rows[0].Cells[0].Text = "No Records Found";
}
}
return ds.Tables[0];
}
public void gvDetails_OnSorting(Object sender, GridViewSortEventArgs e)
{
string sortingDirection = string.Empty;
if (direction == SortDirection.Ascending)
{
direction = SortDirection.Descending;
sortingDirection = "Desc";
}
else
{
direction = SortDirection.Ascending;
sortingDirection = "Asc";
}
DataView sortedView = new DataView(BindGridView());
sortedView.Sort = e.SortExpression + " " + sortingDirection;
gvDetails.DataSource = sortedView;
gvDetails.DataBind();
}