0

I have a user control that contains a GridView. I pass an IEnumerable data source object to the user control instance. How can I use a ForEach to loop through the data source in the user control code behind to display the columns I want from the data source?

So far, I have the following code in the code behind of the user control:

public IEnumerable<object> DataSource { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    this.GridView1.DataSource = DataSource;

    foreach (var item in DataSource)
    {
//The line below gives an error - what's the correct way to do this?
        this.GridView1.Columns.Add(new BoundColumn() {DataField = "What to put here", HeaderText = "What to put here"; }

    }

    this.GridView1.DataBind();
}
Theomax
  • 6,584
  • 15
  • 52
  • 72

1 Answers1

2

You should not loop on all items of the DataSource, you are looping vertically on all records while you want to loop only once, horizontally, on all columns. Since you know the list of properties of the object contained in the DataSource you can do this statically and not even in a foreach. If you really want to have it dynamic then you could use Reflection and loop on all public fields of the first object available in your IEnumerable.

Edit: to find all public fields of an object via reflection see here:

How can I find all the public fields of an object in C#?

but this only applies if you want to make it generic, if you already know that your object contains some fields like Name, Address and Email, for example, you do not need it.

Community
  • 1
  • 1
Davide Piras
  • 43,984
  • 10
  • 98
  • 147
  • Thanks for your reply. I think I need a code example as I don't understand. – Theomax Sep 19 '11 at 15:17
  • At the moment I don't want to make it generic. I want to know how to specify which columns to use in the gridview from the data source object. – Theomax Sep 19 '11 at 15:26
  • so please edit your question showing the properties of the object inside your IEnumerable. why is that an IEnumerable and not an IEnumerable ?? – Davide Piras Sep 19 '11 at 15:33