user1550951
user1550951

Reputation: 379

Display a record as the first row

I have a GridView in asp.net page.

I am fetching records from a SQL DB and binding this grid to it. The query to bind the grid looks like this:

Select column1,column2,column3 from Table where condition=value.

In the Gridview, column1 is a LinkButton. I have to select 1 random record and this should be the first record in the grid - and the only 'clickable' linkbutton.

All the other records will still be displayed in the grid but none of the linkbuttons will be enabled. I have the query for selecting the random record in SQL:

Select top 1 column1 from Table where condition=value order by newid()

My question: How do I make this random record as the 1st record in the grid.

Upvotes: 0

Views: 326

Answers (1)

Zohar Peled
Zohar Peled

Reputation: 82504

It's not very clear if you want only the first record to be random or all of the records in the gridview in random order.

for sorting all of the records in a random order simply add order by newid() to your query. However, if you only want the first record to be a random one, and keep the order of the other records, you can do something like this:

SELECT column1, column2, column3, RowNumber
FROM (
    SELECT column1, column2, column3, ROW_NUMBER() OVER (ORDER BY NEWID()) As RowNumber
    FROM table
    WHERE condition
) InnerSelect
ORDER BY CASE WHEN RowNumber = 1 THEN -1 ELSE column1 END

Note: the -1 in the order by clause is assuming that column1 is an integer and has only values that are 0 or higher. you will need to change it to another value appropriate to the values in the column you wish to order by the rest of the result set if this is not the case.

Upvotes: 1

Related Questions