Cannot apply indexing with [] to an expression of type 'object'!

A

Adam J Knight

Hi all,
I am getting the following error with this if statement..
if(e.Item.DataItem["QuestionType"] != 2)
{
}
//error
Cannot apply indexing with [] to an expression of type 'object'

Can someone fill me in on what is happening?

Error occurs in a datalist's ItemBound events. The datasource is a
dataset..
Cheers,
Adam
 
K

Kevin Lawrence

You have to cast the DataItem as a DataSet, ie:

if ((e.Item.DataItem as DataSet)["QuestionType"] != 2)

Kev
 
M

Matt Dinovo

You can accomplish what you're attempting one of two ways.

1) You can cast e.Item.DataItem to a DataRowView, for example if you were
binding to a data set, and get the value from that:

DataRowView drv = (DataRowView)e.Item.DataItem;
if(drv["QuestionType"]!=2){...}

2) You can use the DataBinder to evaluate against the DataItem:

if(Convert.ToInt32(DataBinder.Eval(e.Item.DataItem,
"QuestionType"))!=2){...}

Either one of these should work for you. I recommend the first approach if
you're evaluating several items within the event.

HTH,

Matt Dinovo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top