0
votes

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();
}
1

1 Answers

2
votes

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.