Using the SqlDataReader Class - Returning Fields in appropriate data types
(Page 6 of 6 )
In the following example we use the SqlDataReader.GetString() method and the SqlDataReader.GetInt16() method to retrieve the fields of the job_desc and job_id columns in appropriate data types without performing any data type conversion operations. The GetString() method returns the field as a string value and the GetInt16() method returns the field as a short value, as in the following example.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
using (SqlConnection connection = new SqlConnection
(connectionString))
{
string commandText = "SELECT job_id, job_desc FROM Jobs";
SqlCommand command = new SqlCommand(commandText, connection);
connection.Open();
using (SqlDataReader dataReader = command.ExecuteReader())
{
while (dataReader.Read())
{
string jobDesc = dataReader.GetString(dataReader.GetOrdinal
("job_desc"));
short jobId = dataReader.GetInt16(dataReader.GetOrdinal
("job_id"));
ListItem item = new ListItem();
item.Text = jobDesc;
item.Value = jobId.ToString();
DropDownList1.Items.Add(item);
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
Label1.Text = "The list item " + DropDownList1.SelectedItem + "
has value of " +
DropDownList1.SelectedValue;
}
We simply declared a string variable, the jobDesc variable, and a short variable called jobId, and assigned the values of the fields that we got from the SqlDataReader object to them without making any data type conversion operations. Note that we called the jobId.ToString() method to assign value to the ListItem.Value property because it accepts a string value. So if you know that you are retrieving a string value, use the GetString() method; if you know that you are retrieving a BIT data type from SQL Server table, use the GetBoolean() and so on.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |