Académique Documents
Professionnel Documents
Culture Documents
9.3.2. Reading
The next thing we probably want to do is read from the database. To do this, we need to create and invoke a
query, and collect the results. Here is an example that checks a UCAS number (just think of it as a username if
you are not familiar with UCAS) and a password, and then attempts to retrieve information based on that.
string UCAS = UCASNumber.Text;
string pass = Password1.Value;
try
{
VisitConnection.Open();
SqlCommand cmd =
new SqlCommand("select * from Applicant where
UCAS=@UCAS",VisitConnection);
cmd.Parameters.Add("@UCAS",SqlDbType.VarChar);
cmd.Parameters["@UCAS"].Value = UCAS;
command.Parameters.Add("@UCAS",SqlDbType.VarChar);
page 9
command.Parameters["@UCAS"].Value = Session["UCAS"];
command.Parameters.Add("@Id",SqlDbType.VarChar);
command.Parameters["@Id"].Value = e.Item.Cells[0].Text;
command.ExecuteNonQuery();
Notice the command ExecuteNonQuery() - previously, with the select operation, we used
ExecuteReader(). ExecuteNonQuery does actually return an int, which we can as here choose to
ignore. However, it does include useful information (usually the number of rows affected, or -1 in the event
of errors). Also, it can throw SqlException - though unlike Java, in C# we are not obliged to write code to
catch it.
Fig.10. SqlDataSource
Click on 'Configure Data Source' and you'll get a configuration wizard - select your database, and follow the
steps:
page 10
Fig.13. GridView
And... that's it. Build and debug:
page 12
Notice that as well as the highlighted property for Select, there are also properties for insert, update and delete.
We are going to modify our example to allow data to be updated. First, we set the update query string. Click on
the UpdateQuery property, and enter the following SQL:
UPDATE Table1 SET event =@event WHERE year=@year
You can either just type it in or use the Query Editor. You can also, if you've specified primary keys (which we
haven't) get the setup wizard to do this for you automatically - or at least have a good attempt at it. Note that
what we are doing here is simple but very insecure - see the Security chapter for more information.
Now, select the GridView control, click the small triangle to bring the dialogue back up, and click 'Add New
Column:
page 15