Click here to Skip to main content
16,015,623 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have some problem with GridView Control validations. I have Asp CheckBox at first column in all the rows of my GridView, I need to delete all the rows which are selected through CheckBox.
So i have to check whether the row is selected or not using (CheckBox). But when i am catching the result at runtime to check whether its checked or not, i am getting an error. The error is raised at catching the boolean result to (bool b)

Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.CheckBox'.

The code i used is:
C#
bool b = ((CheckBox)GridView1.Rows[i].Cells[0].Controls[0]).Checked;
if(b)
{ 
   string strid=(string)GridView1.Rows[i].Cells[1].Text; 
  cusidlist.Add(strid);
}


Thanks.....
Posted
Updated 13-Jun-10 20:19pm
v2

sarath.mk wrote:
Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.CheckBox'.


Error is self-explanatory. You have used a Literal Control to present as checkbox while creating the grid. Now, while getting the values you are trying to cast that control into checkbox.

Solution:
Just cast it into the same control-type that you used to create it.
 
Share this answer
 
You cannot convert another control to a checkbox.
You need to make sure GridView1.Rows[i].Cells[0].Controls[0]) is a checkbox.
 
Share this answer
 
v2
Hai Sandeep Mewara,

Can u pls explain how to create a literal control and to type cast the result to the same literal control. I tried it but not able to cast to literal control at that line of code. Can u pls send code for that.

Thanks in Advance.....
 
Share this answer
 
The control here:

GridView1.Rows[i].Cells[0].Controls[0].


is of type Literal, so you can't cast it to a checkbox. What is the control at Controls[1]?

It may be that you've got more than one control in the controls collection in that cell?
 
Share this answer
 
Hai, i found the solution myself to this, since the page is refreshing for every event fire(DeleteAll Button Event), all the checked checkboxes are unchecking so its returning false and its not adding to list and not able to delete the list items(checked items for grid).

So in page load i gave page postback property so the gird will load only for first time and will not uncheck the checkbox when other events fire in the same page.

Later after deleting the checked rows, set page PostBack property to true again so the grid will get refreshed.
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900