Database Reference
In-Depth Information
{
while (rdr.Read())
{
listBox1.Items.Add(rdr[0].ToString());
}
rdr.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
Run the application, and click the button on the form. Within a few seconds,
the list box populates with names from the Users table.
The key is that you can replace the connection string with your local connection string, and it still
works. This is because you're using ADO.NET to handle the connection, and it doesn't care where the
database is. Next, let's take this example one step further and look at how you use datasets.
3.
Using a Dataset
In the last example, you found that there is no difference in using a SqlDataReader when querying a SQL
Azure database. This example uses the SqlCommand class and the SqlDataAdapter to query SQL Azure and
populate a dataset. Here are the steps:
1.
In the button's click event, replace the existing code with the following:
using (SqlConnection conn = new SqlConnection(connStr))
{
try
{
using (SqlCommand cmd = new SqlCommand())
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter();
cmd.CommandText = "SELECT Name FROM Users";
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
DataSet ds = new DataSet("Users");
da.Fill(ds);
listBox1.DataSource = ds.Tables[0];
listBox1.DisplayMember = "Name";
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
Search WWH ::




Custom Search