2

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

3 Answers 3

5

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Worked out that all my existing code was right, just needed the command string. It worked, so thanks.
1

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

Comments

0

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

1 Comment

SqlCommand implements IDisposable too - why not have that in a using statement as well?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.