Reputation: 117
I am retrieving my toyName from database and want to session it over to the next page. My session has nothing wrong but I have this error which state as below and i not sure where have i gone wrong. I have 2 link buttons in my .aspx page and this link button that is having error is the second linkButton i created.
Error Message:
Unable to cast object of type 'ASP.Catalogue_aspx' to type 'System.Web.UI.WebControls.LinkButton'.
Source Error:
Line 13: protected void Page_Load(object sender, EventArgs e)
Line 14: {
Line 15: LinkButton LinkButton = (LinkButton)sender;
Line 16: int toyID = Convert.ToInt32(LinkButton.CommandName);
Line 17:
Here is my page_load .cs code:
protected void Page_Load(object sender, EventArgs e)
{
LinkButton LinkButton = (LinkButton)sender;
int toyID = Convert.ToInt32(LinkButton.CommandName);
string strConnectionStr = ConfigurationManager.ConnectionStrings["ASPNETConnectionString"].ConnectionString;
string sql = "SELECT toyID, toyName FROM Toys WHERE toyID=@toyID";
SqlConnection myConnect = new SqlConnection(strConnectionStr);
myConnect.Open();
SqlCommand command = new SqlCommand(sql, myConnect);
command.Parameters.AddWithValue("@toyID", toyID);
SqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
Label1.Text = dr["toyName"].ToString();
}
dr.Close();
myConnect.Close();
}
Upvotes: 0
Views: 582
Reputation: 4918
You can't cast a page as a link button.. that's never going to work. When you are casting the sender in the page load you are technically casting the page
If you want to use session you need to put
session["something"]= what ever you are trying to save
Then to retrieve it
var myVariable = session["something"] (maybe cast this as something)
Other than that I am not sure what you are trying to do
Upvotes: 0
Reputation: 887857
That's totally wrong.
The sender
for Page_Load
is the page, not a LinkButton
.
Upvotes: 1