Click to See Complete Forum and Search --> : How to display data from database alphabetically under alphabet headings


sophipio@yahoo.
12-02-2005, 01:50 PM
Hi,

I have a database with a table called merchant and it has the following fields :
1)MerchantID - GUID - Merchants ID
2)MerchantName - varchar(50) - Name of the merchants
3)MerchantPoints - varchar(50) - Points the merchants give
4)MerchantURL - varchar(100) - website of the merchants



I am using asp.net and C#. I want the records from the merchant table to be displayed in the following format alphabetically with the corresponding alphabets as headers and the corresponding data under each header.

Example
--------

A

Amazon
American Express
Avon

B

Barnes & Nobles
Bath and Body

C

Corbis
Countdown
Cosmetic Mall
Crayola Stores

D

Direct2Drive
Discount Contact Lenses
DogToys.com

and so on. And each of the above merchant name must be linked to the MerchantURL in the merchant table.
I have just started programming in C# can sometell me which is the best way to do it.

Thanx in advance,

Sophia

Cipher
12-03-2005, 03:05 AM
Did you try "ORDER BY MerchantName" in your sql statement?!

Cstick
12-03-2005, 11:29 PM
Fetch the data using ORDER BY as described by Cipher. Then something like this would work assuming you stored the results into a datatable (Its in VB, but you should get the idea. I did not add any error handling which should be considered as well.):

Dim Output As New System.Text.StringBuilder
Dim cAlpha As String = ""

For Each Dr as DataRow In Dt.Rows
If Not Dr.Item("MerchantName").SubString(0,1) = cAlpha Then
cAlpha = Dr.Item("MerchantName").SubString(0,1)
Output.Append("<div>" & cAlpha & "</div>")
If Output.Length > 0 Then Output.Append("</ul>")
Output.Append("<ul>")
End If

Output.Append("<li><a href=""" & Dr.Item("MerchantURL") & """>" & Dr.Item("MerchantName") & "</a></li>")
Next
Output.Append("</ul>")