Get a Random Row From a SQL Databse with ASP.NET 4.0 and C#
Selecting random rows from a database can be useful for many different purposes such as displaying random images, quotes, products, or anything else that your database may contain. In this example we will choose a random number from a database.
Adding the Default.aspx Page
At this point in the tutorial I have created a new ASP.NET Empty Web Site. What we need to do first is add in a blank Web Form that we will use to test our SQL query and ensure that we are getting the correct results. To do this:
Next, we are going to add a Label and a Button to the Web Form to allow us to test our SQL query. To do this, open Default.aspx up to Design mode and:
Next, we need to setup a simple databse that we will be using to select a random row from. In this case, I’m going to create a database with a table named Numbers that will contain 1 column, Number, and will have 10 different rows with the numbers 1 through 10 in them. To do this:
Next, we need to add in a connection string to our Database that we will use to send our SQL query. To do this, open up the Web.Config file for editing. In the <configuration> tag, above the <system.web> tag, we need to add the following for our connection string:
This will establish a connection to the Database.mdf we added earlier.
If you’re looking for a really good web host, try Server Intellect – we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!
Adding the SQL Query
Next, we need to add in the code that will send the SQL query to our database and select a random row from our Numbers table. To do this, open the Default.aspx up to Design mode and:
Try Server Intellect for Windows Server Hosting. Quality and Quantity!
Testing
To test this out and ensure that we are indeed selecting random rows, load up the website and click the button that we added. Notice that the label displays a random number, 1 through 10, which corresponds to the selected row in the database.
Get RandRow Sql ASP4 csharp
Adding the Default.aspx Page
At this point in the tutorial I have created a new ASP.NET Empty Web Site. What we need to do first is add in a blank Web Form that we will use to test our SQL query and ensure that we are getting the correct results. To do this:
- Right click the project in your Solution Explorer.
- Select Add New Item…
- Select a Web Form and name it Default.aspx.
- Click Add.
Next, we are going to add a Label and a Button to the Web Form to allow us to test our SQL query. To do this, open Default.aspx up to Design mode and:
- Drag and drop a Label Control onto the Web Form.
- Insert a line break to the right of the Label.
- Drag and drop a Button Control under the Label.
- Change the Text property of the Button to ‘Click Me’.
Next, we need to setup a simple databse that we will be using to select a random row from. In this case, I’m going to create a database with a table named Numbers that will contain 1 column, Number, and will have 10 different rows with the numbers 1 through 10 in them. To do this:
- Right click the project in your Solution Explorer.
- Select Add ASP.NET Folder -> App_Data.
- Right click the App_Data folder.
- Select Add New Item…
- Choose a SQL Server Database and use the default name Database.mdf.
- Click Add.
- In the Server/Database Explorer with your Database.mdf expanded, right click the Tables folder.
- Select Add New Table.
- Add a New Column named Number, with a Data Type of int.
- Save the table as Numbers.
- Right click the Numbers table in the Server/Database Explorer and select Show Table Data.
- Add in the numbers 1 – 10 to new rows respectively.
Next, we need to add in a connection string to our Database that we will use to send our SQL query. To do this, open up the Web.Config file for editing. In the <configuration> tag, above the <system.web> tag, we need to add the following for our connection string:
Code Block
Web.Config
The connection string to our database.<connectionStrings>
<add name="NumbersConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
If you’re looking for a really good web host, try Server Intellect – we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!
Adding the SQL Query
Next, we need to add in the code that will send the SQL query to our database and select a random row from our Numbers table. To do this, open the Default.aspx up to Design mode and:
- Double click the button to generate a click event method.
- At the top of the Default.aspx.cs we need to add the following using statements:
Code BlockDefault.aspx.csThe using statements we need for sending SQL Queries.using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration; - In the Button1_Click event method, we need to add the following code:
Code BlockDefault.aspx.csThe code to send our SQL query.protected void Button1_Click(object sender, EventArgs e)
{
//Create a connection to our Numbers database, using the connection string we added to the Web.Config file
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["NumbersConnectionString"].ConnectionString);
//Create our SQL command to select a random row
SqlCommand cmd = new SqlCommand("SELECT TOP 1 Number FROM Numbers ORDER BY NEWID()", conn);
cmd.CommandType = CommandType.Text;
//open the connection and send the query
using (conn)
{
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
//Set our text to the random number selected
Label1.Text = rdr["Number"].ToString();
}
}
}
Try Server Intellect for Windows Server Hosting. Quality and Quantity!
Testing
To test this out and ensure that we are indeed selecting random rows, load up the website and click the button that we added. Notice that the label displays a random number, 1 through 10, which corresponds to the selected row in the database.
Get RandRow Sql ASP4 csharp
