This document provides steps to create a simple web form application in Visual Studio that connects to a SQL database and retrieves data from a table to display on an ASP.NET web page. It describes how to create a database and table, get the connection string, write C# code behind to connect and execute a command to retrieve data from the table, and render the results on the web page.
20. See next slide for what it should look like when you put it in the code
21. Connect String You need to modify the connect string that you extract from the properties of the Database so that the compiler will accept it. Here is a sample connect string: Data Source=.SQLEXPRESS; AttachDbFilename=|DataDirectory| MyDatabase.mdf;Integrated Security=True;User Instance=True;
38. Open connections are like open pipes to the database – you will need to close it when you are done
39.
40.
41. See comments in code on the next slide as to how data is extracted form the reader
42. Extracting Data from a SqlDataReader When you extract data from a reader, you should be aware of the data type you are extracting and how it maps to the language (.net) data types
43. Code to iterate through a reader while (reader.Read()) { //my_varchar is varchar which maps to .net string so use GetString string name = reader.GetString(0); //my_int is int which maps to Int32 Int32 id = reader.GetInt32(1); //now that I have loaded the data into c# string I can output //here I'm using response.write to output directly to the //browser. //I concatenate the data with html to produce the 'layout' //I want Response.Write(name + " " + id + "<br />"); }
44.
45. If you don't close the connection you will run into problems with the database – it will think you are still connected
46.
47. This will force your code to compile and bring up a browser window with the response
48. To do this right click on the .aspx file in the solution explorer and choose to 'View in Broswer'