简体   繁体   中英

Convert Custom Object To DataRowView C# WinForms

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 ??

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 (eg 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.

eg

<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"]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM