e.Row.DataItem error in gridview rowdatabound event

rockenpeace picture rockenpeace · Jan 14, 2014 · Viewed 24.5k times · Source

enter image description here I want to enable or disable a particular row according to the related user logined. So i use rowdatabound event but i have an error in this line:

DataRow drv = ((DataRowView)e.Row.DataItem).Row; 

In here, e.Row.DataItem has related row information. I have controlled and it has values of row. But when i want to continue, i take this error:

Unable to cast object of type '<>f__AnonymousType014[System.Int32,System.Int32,System.String,System.String,System.DateTime,System.String,System.String,System.String,System.String,System.String,System.String,System.Nullable1[System.DateTime],System.String,System.Nullable`1[System.Boolean]]' to type 'System.Data.DataRowView'.

Then I have changed this line:

DataRowView drv = e.Row.DataItem as DataRowView;

For this condition, it gives no error but drv has still null value. Dataitem does not assign its value.

In here, related full code:

protected void gvListele_RowDataBound(object sender, GridViewRowEventArgs e)
{
    dbeDataContext db = new dbeDataContext();
    var c = (from v in db.CAGRIs where v.UserID != Convert.ToInt32(Session["user"]) select v).ToArray();
    if (c != null)
    {
        foreach (var item in c)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                 DataRow drv = ((DataRowView)e.Row.DataItem).Row; 

                int tempID = Convert.ToInt32(drv["CagriID"].ToString());
                if (item.CagriID == tempID)
                {
                    e.Row.Enabled = false;
                }
            }
        }
    }
}

What can i do for this error ? Thanks in advance.

Answer

rockenpeace picture rockenpeace · Jan 16, 2014

I have solved my problem two days ago. I've used this:

int callID = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "CagriID"));

All the event:

    protected void gvListele_RowDataBound(object sender, GridViewRowEventArgs e)
{
    dbeDataContext db = new dbeDataContext();
    var c = (from v in db.CAGRIs where v.UserID != Convert.ToInt32(Session["user"]) select v).ToArray();
    if (c != null)
    {
        foreach (var item in c)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int callID = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "CagriID"));
                if (callID == item.CagriID)
                {
                    e.Row.Enabled = false;
                    continue;
                }
            }
        }
    }
}