3
protected void Page_Load(object sender, System.EventArgs e)
{
    DataTable dt = GetDataTable("select * from AccountTypes");

    repeater.DataSource = dt;
    repeater.DataBind();
}

private void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType != ListItemType.Item) {
        return;
    }

    var row = (DataRow)e.Item.DataItem;
}

It throws exception that "Unable to cast object of type 'System.Data.DataRowView' to type 'System.Data.DataRow'."

DataRow is an element of DataTable, but why does e.Item.DataItem become DataRowView?

Can anyone find a MSDN documentation mentioning this?

Gqqnbig
  • 5,845
  • 10
  • 45
  • 86
  • I am not sure why the thing is doing what it does, perhaps because repeater produces `DataRowView` objects. Obviously, using `var row = ((DataRowView)e.Item.DataItem).Row;` will fix this problem. – Sergey Kalinichenko Oct 05 '17 at 17:12
  • Not sure why you are getting DataRowView - which is a custom version of DataRow, but you can use it as DataRow as this - https://stackoverflow.com/questions/17089147/a-way-to-get-a-datarow-from-a-datarowview – Ziv Weissman Oct 05 '17 at 17:12

3 Answers3

4

This behavior is defined by the DataTable class. Unlike a typical collection class, DataTable implements IListSource instead of IEnumerable. The IListSource interface allows a class to "customize" the data provided to data-binding controls like Repeater.

DataTable's IListSource implementation returns DefaultView, so

repeater.DataSource = dt;

is actually equivalent to

repeater.DataSource = dt.DefaultView;

The type of DefaultView is DataView, which is a DataRowView collection. And that's why your data items are DataRowView objects.

Michael Liu
  • 52,147
  • 13
  • 117
  • 150
2

DataRowView encapsulates a DataRow, adding binding functionality that is useful in the context of web controls (like Repeaters).

If you want to interact with the underlying Row, just use the Row property, like this:

var row = e.Item.DataItem.Row;

This is a possible duplicate of How can Convert DataRowView To DataRow in C#.

Paul Smith
  • 3,104
  • 1
  • 32
  • 45
0
protected void Page_Load(object sender, System.EventArgs e)
{
    DataTable dt = GetDataTable("select * from AccountTypes");

    repeater.DataSource = dt;
    repeater.DataBind();
}

private void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType != ListItemType.Item) {
        return;
    }

    var row = e.Item.DataItem;
}