0

I have a function in an application:

private void ds_ItemBound(object sender, DataGridItemEventArgs e)

where in this line:

((System.Web.UI.WebControls.CheckBox)(e.Item.Cells[3].Controls[0])).Checked = false;

I get an exception:

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

How do I solve this casting error?

Thanks for your help.

5
  • pls verify e.Item.Cells[3].Controls[0] control type is label or checkbox, you can check it on quick watch e.Item.Cells[3].Controls[0] while debugging Commented Apr 6, 2017 at 6:04
  • Please provide the DataGrid markup so we can have a better idea of what we are looking at here. Commented Apr 6, 2017 at 6:13
  • @JigneshVariya e.Item.Cells[3].Controls[0] is System.Web.UI.LiteralControl Commented Apr 6, 2017 at 6:18
  • @JonP the check box markup looks like <asp:CheckBox ID="lblEditCheck" runat="server" TabIndex="0" Width="30px" CssClass="ColumnHeader" /></td> Commented Apr 6, 2017 at 7:02
  • But we are still lacking where it sits in the DataView. Please provide that context in the question itself Commented Apr 6, 2017 at 22:55

2 Answers 2

2

It would seem that your first control in the forth column is not a checkbox. I would advise using the FindControl function instead of your args' Item property.

private void ds_ItemBound(object sender, DataGridItemEventArgs e)
{
    if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;

    var checkbox = (CheckBox) e.Item.FindControl("lblEditCheck");
    checkbox.Checked = false;
}
Sign up to request clarification or add additional context in comments.

3 Comments

e.Item.Cells[3].Controls[0] is System.Web.UI.LiteralControl . Thanks for the help.
You might find that you're getting an ItemBound even for the header/footer row or something like that. Added a check to my sample accordingly.
Hi, thanks for the answer. However I still get the error, now I get that checkbox variable is null. I still don't get how to resolve the error. The problem is that I have multiple rows that should be populated in a table, I get only one row + an exception :(
0

Make sure your CheckBox is first in the fourth cell, it looks like there's a Literal. Please post fragment of your page code to confirm.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.