Andre C
Andre C

Reputation: 487

Get data from SQL Server database into label

In my ASP.Net webpage, I have a label and need the label's text to be retrieved from my database.

I have no problem writing to my database, but it seems trying to retieve the data again is a mission...

What I need is to get the data from the Price column in my database, from the table Tickets, from the record where the ConcertName data is the same as my webpage's title, or a string associated with my webpage.

I have tried many tutorials already, but all just throw me errors, so I decided to try one last place before I just give in and make my labels static.

In case it helps, I have tried the following:

First Try

Second Try

Third Try

Fourth Try

Upvotes: 2

Views: 35418

Answers (3)

NuNn DaDdY
NuNn DaDdY

Reputation: 2992

Here is an example protecting against SQL Injection and implicity disposes the SqlConnection object with the "using" statement.

string concert = "webpage title or string from webpage";

using(SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["connString"].ConnectionString))
{
   string sqlSelect = @"select price 
                        from tickets 
                        where concert_name = @searchString";
   using(SqlCommand cmd = new SqlCommand(strSelect, conn)) 
   {
      cmd.Parameters.AddWithValue("@searchString", concert);
      conn.Open();
      priceLabel.Text = cmd.ExecuteScalar().ToString();
   }
}

If you're interested in researching ADO .Net a bit more, here is a link to the MSDN documentation for ADO .Net with framework 4.0

http://msdn.microsoft.com/en-us/library/h43ks021(v=vs.100).aspx

Upvotes: 0

Coltech
Coltech

Reputation: 1710

Looks like you want to bind the label to a data source. Here is a great example that works.

Upvotes: 1

PraveenVenu
PraveenVenu

Reputation: 8337

Hopes you use c#

string MyPageTitle="MyPageTitle"; // your page title here
string myConnectionString = "connectionstring"; //you connectionstring goes here

SqlCommand cmd= new SqlCommand("select Price from Tickets where ConcertName ='" + MyPageTitle.Replace("'","''") + "'" , new SqlConnection(myConnectionString));
cmd.Connection.Open();
labelPrice.Text= cmd.ExecuteScalar().ToString(); // assign to your label
cmd.Connection.Close();

Upvotes: 5

Related Questions