我正在创建带有DataGridView
的自定义USERCONTROL,我将此UserControl添加到我的表单中。在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; }
}
}
}
您的问题是您在额外的类中创建自定义控件,但切勿将控件添加到要显示的表单
一条简单的行将解决您的问题:
this.Controls.Add(uc);
将其放入构造函数。这将确保将您的自定义控件添加到Form
中以进行显示
编辑:
当然还有一种手动方法:这是带有屏幕截图的答案,如何将新的用户控件添加到工具箱或新的Winform?
这是另一个:将用户控件添加到表单
dataGridView在用户控件中。这就是为什么您的datagrid不用以用户控件加载的表单。
-
转到usercontrol.cs
-
在构造函数中粘贴以下代码
; this.studentTableDapter.fill(this.universitydataset.student);
在我的情况下,数据集是UniversityDataSet,桌子是Student