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
215How can I easily work with/manipulate/parse file paths in .NET?31569
142How can I use application-level variables to cache information?97894
159Where can I learn more about ASP.NET?55617
166How can I secure an Access database that I use on my Web site? That is, I don't want users to be able to guess the URL of my Access .mdb file and download my database!81254
165How can I rename a directory on my Web server?54063
13How do you send email attachments through an ASP page?111649
200What is the easiest way of extracting certain data from an XML document?54493
48How can I add or subtract time from a date?80966
134How can I execute ASP pages on Windows 9X? (How do I install Personal Web Server?)59898
31How do I set a string variable so that it has quotes in it? I want a variable to equal: Bob said, "Hello."57236


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]