Search code examples
c#winformsdevexpressxtragrid

Programmatically create columns in a View


This should be easy. I want to populate a grid with a custom data source at runtime. For some reason, it simply does not work.

Running via a unit test

[TestMethod]
public void Runtest() {
    TestForm form = new TestForm();
    TestControl control = new TestControl();
    form.Controls.Add(control);
    control.LoadData();
    form.ShowDialog();
}

The relevant Control code

public void LoadData() {
    SourceRecord[] original = new SourceRecord[] { 
        new SourceRecord("1"), new SourceRecord("3"), new SourceRecord("9") };
    gridControl1.DataSource = original;
    GridColumn col = gridView1.Columns.AddVisible("SomeColumn");
    col.FieldName = "SomeName";
    //gridControl1.ForceInitialize();
}

Record info

public class SourceRecord {
    public string SomeName = "";
    public SourceRecord(string Name) {
        this.SomeName = Name;
    }
}

I end up with some column just called "Column" which displays 3 rows reading ClassLibrary1.SourceRecord. Then my custom column "Some Name" has no data. According to the devexpress walkthrough I only need to populate the DataSource with a class that implements IList, which I did with an Array.

How can I display just my custom column and give it the data?


Solution

  • The grid control will bind columns to properties only. Try this:

    public class SourceRecord
    {
        public string SomeName { get; set; }
        public SourceRecord(string Name)
        {
            SomeName = Name;
        }
    }
    
    public void LoadData()
    {
        SourceRecord[] original = new SourceRecord[] { new SourceRecord("1"), new SourceRecord("3"), new SourceRecord("9") };
        GridColumn col = gridView1.Columns.AddVisible("SomeColumn");
        col.FieldName = "SomeName";
        gridControl1.DataSource = original;
    }