My web page should allow me to select a title of a book from a drop-down list, press the select button, and textboxes(ie. Author, Year, Category) should change according to the book selected. However, when I select the second book from the list, it always loops back to show the details of the 1st book on the dropdown list, no matter what I select, it always only shows the first record.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
LoadDetails();
}
private void LoadDetails()
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString =ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT BookId, Title FROM Books", conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
ddlSearch.DataSource = reader;
ddlSearch.DataValueField = "BookId";
ddlSearch.DataTextField = "Title";
ddlSearch.DataBind();
reader.Close();
}
catch
{
lblError.Text = "Error loading books";
}
finally { conn.Close(); }
}
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString =ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT ISBN, Author, Title, Year, Category FROM Books Where BookId=@BookId", conn);
comm.Parameters.Add("@BookId", System.Data.SqlDbType.Int);
comm.Parameters["@BookId"].Value = ddlSearch.SelectedItem.Value;
try
{
conn.Open();
reader = comm.ExecuteReader();
if (reader.Read())
{
txtIsbn.Text = reader["ISBN"].ToString();
txtAuthor.Text = reader["Author"].ToString();
txtTitle.Text = reader["Title"].ToString();
txtYear.Text = reader["Year"].ToString();
txtCat.Text = reader["Category"].ToString();
}
}
catch
{
lblError.Text = "Error laoding pages";
}
finally
{
conn.Close();
}
}
I've tried many different variations of code but it doesnt seem to be working. It probably is a simple enough fix but I can't put my finger on it. Any help appreciated. Thanks!