Display Alphabetically Sorted Data in a Data Grid


Introduction:

This code samples shows how to 

  • Display the data alphabetically based on the values in the database.

To begin with Code:

Drag Drop the Repeater on the webform

<asp:Repeater id="Repeater1" runat="server"></asp:Repeater>

For simple binding of the Data to the Repeater Code would be as below:

<asp:Repeater id="Repeater1" runat="server">
<%#DataBinder.Eval(Container.DataItem, "LastName").ToString()%>,
<%#DataBinder.Eval(Container.DataItem, "FirstName").ToString()%>
<br>
</
asp:Repeater> 

In code behind

C#

SqlConnection cn;
SqlDataAdapter da ;
DataSet ds ;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(!Page.IsPostBack)
{
//Code to Bind the data to the Datagrid
cn = new SqlConnection("Server=localhost;uid=sa;pwd=;database=northwind;");
da =
new SqlDataAdapter("Select * from employees order by lastname", cn);
ds =
new DataSet();
da.Fill(ds,"Table");
Repeater1.DataSource=ds;
Repeater1.DataBind();
}
}

VB.NET

Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not Page.IsPostBack Then
cn = New SqlConnection("Server=localhost;uid=sa;pwd=;database=northwind;")
da =
New SqlDataAdapter("Select * from employees order by lastname", cn)
ds =
New DataSet
da.Fill(ds, "Table")
Repeater1.DataSource = ds
Repeater1.DataBind()
End If
End
Sub

To display the contents alphabetically based on the values in the Database

<asp:Repeater id="Repeater1" runat="server">
<
ItemTemplate><b>
<
u><p>
<%#GetFirstAlphabet(DataBinder.Eval(Container.DataItem, "LastName").ToString())%>
</p></u>
</b>
<%#DataBinder.Eval(Container.DataItem, "LastName").ToString()%>,
<%#DataBinder.Eval(Container.DataItem, "FirstName").ToString()%>
<br>
<
br>
</
ItemTemplate>
</
asp:Repeater>

In the code behind write a Helper function as

C#

protected
string GetFirstAlphabet(string strval)
{
string alphabet =(string) ViewState["alphabet"];
if( alphabet == strval.Substring(0,1) )
{
return "";
}
else
{
alphabet = strval.Substring(0,1);
ViewState["alphabet"] = alphabet;
return alphabet;
}
}

VB.NET

Function GetFirstAlphabet(ByVal strval As String) As String
Dim alphabet As String = ViewState("alphabet")
If alphabet = Left(strval, 1) Then
Return ""
Else
alphabet = Left(strval, 1)
ViewState("alphabet") = alphabet
Return alphabet
End If
End
Function 


Similar Articles