【发布时间】:2019-11-29 01:38:43
【问题描述】:
我正在创建一个带有DataGridView 的自定义用户控件,并且我正在将此用户控件添加到我的表单中。在Form1_Load 事件中,我通过调用用户控件的构造函数来初始化用户控件。它是一个参数化的构造函数,它有一个List 作为参数,并且该列表被用作用户控件中DataGridView 的DataSource。
问题是:DataGridView 没有加载数据。
任何人都可以弄清楚。
表单加载事件中的代码是,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace usercontrol
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<Car> cars = new List<Car>();
cars.Add(new Car("Ford", "Mustang", "1967"));
cars.Add(new Car("Shelby AC", "Cobra", "1965"));
cars.Add(new Car("Chevrolet", "Corvette Sting Ray", "1965"));
ucSample uc = new ucSample(cars);
}
}
public class Car
{
private string company;
private string color;
private string year;
public Car(string com,string col,string yea)
{
this.Company = com;
this.Color = col;
this.Year = yea;
}
public string Company { get; set; }
public string Color { get; set; }
public string Year { get; set; }
}
}
用户控件中的代码是
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace usercontrol
{
public partial class ucSample : UserControl
{
public ucSample()
{
InitializeComponent();
}
public ucSample(List<Car> listString)
{
InitializeComponent();
DataSource = listString;
}
public object DataSource
{
get { return dgvSample.DataSource; }
set { dgvSample.DataSource = value; }
}
}
}
【问题讨论】:
-
DataGridView是否将属性AutoGenerateColumns设置为true? -
是的,我将其设置为 true...
标签: c# winforms datagridview user-controls