Undisputed007
Undisputed007

Reputation: 649

Store object reference in DataGridView row?

I have a method as such :

public void setResults(Documents[] doc)
{

    //I call a method to set the columns 
    setColumns(doc[0].getColumnsToDisplay())

    //Here i populate the DataGrid

   foreach (Documents element in doc)
   {
                     /dt is a datatable
        DataRow dr = dt.NewRow();

        foreach (string col in results[0].getColumnsToDisplay())
        {
          object val;
          (element.getAttributes() as IDictionary<string, object>).TryGetValue(col, out val);
           dr[col] = val.ToString();    
        }
                    dt.Rows.Add(dr);

    }
       gridSearchResults.DataSource = dt;

    }

Is there a way to store "doc" reference on each row ? so that if i select a row, i can be able to return the "doc" object ? Looking for some kind of Tag property alternative for rows or something different.

Upvotes: 1

Views: 3031

Answers (2)

Reza Aghaei
Reza Aghaei

Reputation: 125197

When you want to show a list of your objects in a DataGridView, you don't need to use a DataTable. You can simply set your list as DataSource of your DataGridView:

public void setResults(Documents[] doc)
{
    gridSearchResults.DataSource = doc;
}

Then if you want to know the object behind the row, you can simply use DataBoundItem property of the DataGridViewRow and cast it to your object type:

var documents= (Documents)gridSearchResults.Rows[0].DataBoundItem;

For more information and samples, you can see:

If you want to show only some columns in the DataGridView, add the columns you need this way:

this.dataGridView1.Columns.Clear();
this.dataGridView1.AutoGenerateColumns = false;

//Create Column
var column1 = new DataGridViewTextBoxColumn()
{
    Name = "firstNameColumn",        /*Name of Column*/
    HeaderText = "First Name",       /*Title of Column*/
    DataPropertyName = "FirstName"   /*Name of the property to bind to cilumn*/
};

//Add column to grid
this.dataGridView1.Columns.Add(column1);

Upvotes: 2

Anıl Okay
Anıl Okay

Reputation: 111

You should use DataGridView instead of DataGrid. I assume you're trying to get the object after postback.

//DO NECESSARY NULL CHECKS!!!
DataRow row = (gridSearchResults.SelectedRows[0].DataBoundItem as  DataRowView).Row;
Documents selected = (Documents)row;

Upvotes: 1

Related Questions