Arjun Babu
Arjun Babu

Reputation: 219

Why do I get "InvalidCastException"

I have my code as below

((LinkButton)GridView1.Rows[0].Cells[0].Controls[0]).Text = "INSERT";

I got the error as

Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to type 'System.Web.UI.WebControls.LinkButton'

Upvotes: 1

Views: 352

Answers (2)

mmdemirbas
mmdemirbas

Reputation: 9158

Cast to Control instead of LinkButton if all you need is Text property:

((Control)GridView1.Rows[0].Cells[0].Controls[0]).Text = "INSERT";

By the way, doing this way isn't quite right. You should check possible null's and index overflow issues.

Upvotes: 1

Alexander Pavlov
Alexander Pavlov

Reputation: 32286

Hmmm... The issue seems to be that GridView1.Rows[0].Cells[0].Controls[0] is an object of class TextBox rather than LinkButton. You should fix your gridview contents.

Upvotes: 5

Related Questions