James D
James D

Reputation: 351

Populating a datagridview with a defined class?

So I'm having trouble getting a datagrid to populate with a class I have created. The class looks like so:

public class Shell
{
    public string shellURL { get; set; }
    public string shellStatus { get; set; }

    public Shell(string shellURL, string shellStatus)
    {
        this.shellURL = shellURL;
        this.shellStatus = shellStatus;
    }
}

I tried to do the following method but it's not populating correctly, it's just adding Shell.shelllist or something like that not the actual strings. I want the datagrid to populate with the shell url and shell status.

var source = new BindingSource();
rawShellsDataGrid.AutoGenerateColumns = true;
source.DataSource = shellList.Select(x => new { Shell = x }).ToList();
rawShellsDataGrid.DataSource = source;

How would I go about populating the datagrid with the actual variables of the shelllist list? I find datagrids very tricky, ideally I'd like to predefine the columns but I had absolutely no success with that, just empty columns were added.

I want the datagrid to auto generate the columns of the Shell class and add their values.

Upvotes: 0

Views: 548

Answers (1)

jdweng
jdweng

Reputation: 34421

You can always build a DataTable which is easy to bind

    public class Shell
    {
        public string shellURL { get; set; }
        public string shellStatus { get; set; }

        public Shell(string shellURL, string shellStatus)
        {
            this.shellURL = shellURL;
            this.shellStatus = shellStatus;
        }
        public DataTable BuildTable(List<Shell> shells)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("URL", typeof(string));
            dt.Columns.Add("Status", typeof(string));

            foreach(Shell shell in shells)
            {
                dt.Rows.Add(new object[] { shell.shellURL, shell.shellStatus});
            }

            return dt;
        }|
    }

Upvotes: 2

Related Questions