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
44How can I display Recordset data in an HTML TABLE? How can I get the names of all the fields in a table?64285
207How do I copy or move a file from one location to another?85453
24How can I read the contents of a text file through an ASP page?60479
185What are the differences between C# and VB.NET, and which language should I use to create my ASP.NET Web pages?64405
129Can I create an application-level Dictionary object?76235
52How can I display all of the cookies/cookie values for a user through a Web page?59803
101How can I list all of the Application variables on a Web page?77615
73How can I time the execution speed of my ASP pages to the millisecond?54273
174Why do I get a closed recordset from my stored procedure? Why don't I get the expected fields from the stored procedure?57541
45How can I ensure that a form field has a particular value? (That is, how can I perform form validation?)58110


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]