1

I have a gridview that I populate with values I get from a powershell command. For example my powershell command is get-command. I know the command returns the values. Here is my code however my gridview never shows the data.

ArrayList boxesarray = new ArrayList();

foreach (PSObject ps in commandResults)
    boxesarray.Add(ps.Properties["Name"].Value.ToString());

boxes.DataSource = boxesarray;
boxes.DataBind();

I know the value is there because I replaced the last two lines with a label and was able to see the value.

boxlabel.text = boxesarray[4];

I must be missing something. Help please.

3
  • Can you post the GridView code? Commented May 14, 2012 at 1:25
  • <asp:GridView ID="boxes" runat="server"> </asp:GridView> Commented May 14, 2012 at 2:19
  • might want to add tags for asp.net and webforms? Commented May 14, 2012 at 2:30

2 Answers 2

1

The GridView requires a collection or IEnumerable of classes which have properties, and the properties are mapped to columns.

An array like yours have value typed objects (strings) which has no roperties, so you can't bind the properties to the columns.

ArrayList boxesarray = new ArrayList();

You could create a simple class like this:

public class PropertyContainer
{
    public string Value {get;set;}
}
// NOTE: you can override ToString(); to customize String.Format behaviour
// and to show it in the debugger (althought there's other way for this, using
// DebuggerDisplayAttribute)

And create and populate an array of this class, which will be correctly bound to the datagrid.

foreach (PSObject ps in commandResults)
    boxesarray.Add(
       new PropertyContainer { Value = ps.Properties["Name"].Value.ToString()});

boxes.DataSource = boxesarray;
boxes.DataBind();

Other option is to convert your array to an array of objects using LINQ. You can even use anonymous object if the data grid columns are set to be automatically created.

// anonymous type
var dataForBinding = boxesArray.select(val => new {Value = val});

// array of the class
var dataForBinding = boxesArray.select(val => new PropertyContainer
   { Value = val });

You can bind this data to your gridview, and it will work perfectly.

Sign up to request clarification or add additional context in comments.

1 Comment

how exactly would I use the first option?
0

You can try

.DataSource = (from ps in commandResults 
               select { Name:ps.Properties["Name"].Value.ToString() }).ToList();

Or

.DataSource = (from name in yourarraylist
               select { Name:name.ToString() }).ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.