I'm new to asp, so be patient :p
I have an sql database, with a users table that has username and a colour.
My asp master page is reading the current users username and passing it to the content fine. What I am trying to now do is in the content page grab the colour from the sql table where the username is the current username, and assign it to a string inside the default.开发者_运维知识库aspx.cs file.
How do I do this?
Cheers
Honestly, and don't take this offensively, but perhaps diving straight into writing a database-driven ASP.NET application isn't where you should be starting out.
I would attempt to learn more about the ASP.NET architecture first, learn the language well (VB.NET or C#), and start with something simpler.
With that said, and assuming you're going to attempt this anyway, what you are probably going to want to start out with is ADO.NET. Microsoft, through MSDN, provides a good page full of ADO.NET Code Examples.
You'll have to define a connection string to your database, which may include specifying a third-party driver if you're using a database such as Sybase or MySql, or using an entirely different set of provider classes such as what you'd need for Oracle. Next you'll create a command containing your SQL query and execute the command. You need to consume the results and pull your value out of a result set, and then clean up the close the connection.
Check out the link; hopefully it will get you started. There are a ton of examples of ADO.NET sprinkled across the Interwebs, I'm sure you can find a working example.
If you want to skip ADO.NET and try something a bit more O/R mappery (and are using Microsoft SQL Server), you might be interested in checking out LINQ to SQL.
EDIT
From your comments, your question is about how to read a value from SQL Server. The most basic way is by just opening a SqlConnection, create a SqlCommand, setting the command text, etc etc. There are many tutorials online. Unfortunately you run the risk of Sql Injection attacks that way.
The best way is to set up an OR Mapper, which creates objects for you, that map directly to your database. The best option there would probably be Entity Framework 4. There are plenty of tutorials online.
END EDIT
Probably the best thing to do would be to set a property in your master page, and then have your default.aspx page read the value from the master page, and do whatever it wants with it.
Having said that, it's usually a bad idea to be doing database reads from your UI. Usually you'll want to push that stuff off to another tier, and have your UI focus on just doing UI things.
But, assuming this is just a simple project, then something like the following line should get you where you need to go:
From default.aspx:
string value = (this.Master as YourMasterPageClass).YourProperty;
精彩评论