Demo of Displaying 10 Random Records

This demo illustrates how to modify the SQL statement to select ten random records. You can refresh this page and you will see ten random FAQs displayed in the DataGrid...


FAQ IDQuestionViews
90How can I programmatically list the contents of a directory on the Web server?69860
186I have many duplicate records in my database table. I want to delete all of them except one. How can I do this?63368
61How can I treat some other web page as data on my own site?91306
27How do I get SQL to accept an apostrophe in various queries, such as when I try to add a user named "O'Brien"?79199
22How can I validate an email adress using Jscript?74792
180How can I install Personal Web Server (PWS) onto Windows XP Home edition?116884
50Can I disable the use of session variables on an ASP page-by-page basis?47054
49Can I send my output to a different window or frame than the one that asked for the current ASP page?48632
77Is there a better way to show debug values from my ASP pages than to Response.Write them in the middle of my page or use a JavaScript alert to pop them up?47057
208How do I rename a file or directory?62371


Source Code
<%@ Import Namespace = "System.Data" %>
<%@ Import Namespace = "System.Data.SQLClient" %>
<script language="VB" runat="server">
  Sub Page_Load(sender as Object, e as EventArgs)
    BindData()
  End Sub
	
	
  Sub BindData()
    '1. Create a connection
    Dim myConnection as New SqlConnection(ConfigurationSettings.AppSettings("connectionString"))

    '2. Create the command object, passing in the SQL string
    Const strSQL as String = "SELECT TOP 10 FAQID, Description, ViewCount FROM tblFAQ ORDER BY NEWID()"
    Dim myCommand as New SqlCommand(strSQL, myConnection)

    'Set the datagrid's datasource to the datareader and databind
    myConnection.Open()
    dgRandOrder.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
    dgRandOrder.DataBind()
    myConnection.Close()
  End Sub
</script>

  <asp:DataGrid runat="server" id="dgRandOrder"
         AutoGenerateColumns="False"
         Font-Name="Verdana" Width="85%"
         Font-Size="11pt" HorizontalAlign="Center">
         
    <HeaderStyle BackColor="Navy" ForeColor="White" HorizontalAlign="Center"
                 Font-Size="14pt" Font-Bold="True" />
   
    <Columns>
      <asp:BoundColumn DataField="FAQID" HeaderText="FAQ ID" />
      <asp:BoundColumn DataField="Description" HeaderText="Question" />
      <asp:BoundColumn DataField="ViewCount" HeaderText="Views" />
    </Columns>
  </asp:DataGrid>


[Return to the article]