Jeff
Jeff

Reputation: 55

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

So far this is what I have.

protected void CategoryRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        Object dataItem = e.Item.DataItem;

        // code to pull catid out of dataItem
    }

Here's an example of what dataItem contains after running in debug:

dataItem = { TextCategory = "Radiation (Release or Contamination)", catid = 4, TextResult = "Refer to emergency plan and report under code 332.54(A)" , IsReportable = True }

I want to pull the catid out of the object. I have tried casting it, but all attempts to cast it have been unsuccessful. My goal is to use this catid for a nested repeater's databind.. something like this:

using (NERAEntities entities = new NERAEntities())
{
    var Questions = (from x in entities.Questions
                   where x.CategoryID == catid
                   select new { QuestionText = x.Text }); 


    QARepeater.DataSource = Questions;
    QARepeater.DataBind();
}

Upvotes: 3

Views: 3697

Answers (3)

Icarus
Icarus

Reputation: 63970

The problem is that the DataItem doesn't really have a type per se (it's an Anonymous class). You would need to use this instead:

dynamic dataItem = e.Item.DataItem ;
int catId = dataItem.catid ;

Obviously, this would fail at runtime if the actual object doesn't have a catId property.

Upvotes: 4

beastieboy
beastieboy

Reputation: 883

May be you could try:

protected void CategoryRepeater_ItemDataBound(object sender, 
    RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || 
        e.Item.ItemType == ListItemType.AlternatingItem)
    {
        DataRowView row = (DataRowView)e.Item.DataItem;
        int? catID = row["catid"] as int;
    }
}

Upvotes: 0

Brian Geihsler
Brian Geihsler

Reputation: 2087

Assuming the type of the object you're using is called DataItem, try this:

    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        DataItem dataItem = (DataItem) e.Item.DataItem;

        // code to pull catid out of dataItem
    }

Upvotes: 0

Related Questions