1

I have a custom object as follows

public partial class _AccessionType
{
    private string accessionIdField;
    private string docUrlField;
    /// <remarks/>
    public string AccessionId
    {
        get
        {
            return this.accessionIdField;
        }
        set
        {
            this.accessionIdField = value;
        }
    }
    public string DocUrl
    {
        get
        {
            return docUrlField;
        }
        set
        {
            docUrlField = value;
        }
    }
}

The above object is used as DataSource for DataGridView. I want to convert the above object to DataRowView.

How can I do it ??

Rémi
  • 3,867
  • 5
  • 28
  • 44
Sandhurst
  • 21
  • 1
  • 2

1 Answers1

1

You need to create a list of _AccessionType and assign it to the DataSource property of the grid view.

List<_AccessionType> accessionTypes= new List<_AccessionType>();    
// Add objects to the list
gridView1.DataSource = accessionTypes;   
gridView1.DataBind();

In the designer for gridView1, you need to right click > Edit Columns and add Bound columns. For each bound column give a suitable HeaderText and in the DataField assign the required member property of _AccessionType (e.g. DocUrl)

You cannot retrieve the object from gridView.DataSource back into List<_AccessionType> or even from the GridViewRow into _AccessionType. Inorder to get the values for a grid view row back, you need to define data keys in the grid view for the values you need to retrieve back.

e.g.

<asp:GridView ID="gridView1" runat="server" 
            AutoGenerateColumns="False" DataKeyNames="AccessionId, DocUrl" EnableViewState="true"> 
... 
</asp:GridView>

Later in the code, you can retrieve back these values when you loop through the DataGrid or in a related data grid event handler:

foreach (GridViewRow accessionRow in this.gridView1.Rows)
{
    int accessionID = Convert.ToInt32(gridView1.DataKeys[accessionRow.RowIndex]["AccessionId"]);
}
Rashmi Pandit
  • 23,230
  • 17
  • 71
  • 111
  • Thats what I am doing. But when I try to Cast it to DataRowView DataRowView drv=(DataRowView)gridView1.ListObject; its throwing a cast exception – Sandhurst Nov 17 '09 at 12:33
  • You CANNOT get the DataSource back from the gridview into your object. Instead you can define DataKeys in the gridview and access those values from the rows. – Rashmi Pandit Nov 17 '09 at 12:40
  • I have edited my answer to show how you can access the object from the grid view row. – Rashmi Pandit Nov 18 '09 at 03:37