gpt4 book ai didi

c# - 用户控件数据 gridview 未加载数据

转载 作者:行者123 更新时间:2023-11-30 21:43:52 25 4
gpt4 key购买 nike

我正在创建一个带有 DataGridView 的自定义用户控件,并将此用户控件添加到我的表单中。在 Form1_Load 事件中,我通过调用用户控件的构造函数来初始化用户控件。它是一个参数化的构造函数,它有一个 List 作为参数,该列表用作用户控件中 DataGridViewDataSource

问题是: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 以供显示

编辑:

当然也有手动的方式:这里有一个带截图的答案How do I add my new User Control to the Toolbox or a new Winform?

这是另一个:add user control to a form

关于c# - 用户控件数据 gridview 未加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41265411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com