Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate a UserControl Gridview with a List of Objects

I have a List of an object called "Reasons" that contains two properties "Code" & "Text". I want to use this to fill a UserControl of a Gridview. However, I don't understand how to link the gridview to the List of Reasons and actually set which data to use from the object.

I would assume the approach would be to set the datasource to the List, however, that is not working as it does seem populate the gridview with any rows. Is there a better approach to this problem?

like image 864
ImGreg Avatar asked Dec 03 '22 07:12

ImGreg


1 Answers

I am assuming you're doing this in winform C#. It should be fairly similar in C# codebehind for asp.net. Here's some sample code you can easily customize to your obj type:

/// <summary>
/// The test class for our example.
/// </summary>
class TestObject
{
    public string Code { get; set; }
    public string Text { get; set; }
}

void PopulateGrid()
{
    TestObject test1 = new TestObject()
    {
        Code = "code 1",
        Text = "text 1"
    };
    TestObject test2 = new TestObject()
    {
        Code = "code 2",
        Text = "text 2"
    };

    List<TestObject> list = new List<TestObject>();
    list.Add(test1);
    list.Add(test2);

    dataGridView1.DataSource = list;
    dataGridView1.DataBind();
}
like image 120
scrat.squirrel Avatar answered Dec 11 '22 10:12

scrat.squirrel