使用对象列表填充 UserControl Gridview [英] Populate a UserControl Gridview with a List of Objects
问题描述
我有一个名为原因"的对象列表,其中包含两个属性代码"和文本".我想用它来填充 Gridview 的 UserControl.但是,我不明白如何将 gridview 链接到原因列表并实际设置要使用的对象数据.
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.
我认为该方法是将数据源设置为列表,但是,这不起作用,因为它似乎用任何行填充了 gridview.有没有更好的方法来解决这个问题?
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?
推荐答案
我假设您在 winform C# 中执行此操作.它在 asp.net 的 C# 代码隐藏中应该非常相似.下面是一些示例代码,您可以轻松地根据您的 obj 类型进行自定义:
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();
}
这篇关于使用对象列表填充 UserControl Gridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!