无法访问用户控制组件 [英] Can not access user control component

查看:29
本文介绍了无法访问用户控制组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的用户控件中,我有一个名为 dgvCustomers 的 datagridview,我想在 gridview 中加载客户,例如:

In my user control I have a datagridview named dgvCustomers, I want to load customers in the gridview like:

private void Form1_Load(object sender, EventArgs e)
{
    db = new DatabaseContext();
    dgvCustomers.DataSource = db.Customers.ToList();
}

但是我无法访问datagridview,我该怎么办?

But I can not access the datagridview, how can I do this?

这是我收到的错误:

名称 dgvCustomers 在当前上下文中不存在.

The name dgvCustomers does not exists in the current context.

用户控件的名称是 CCCustomers.

The name of the user control is CCCustomers.

推荐答案

您的 datagridview 对用户控件私有.您可以通过检查自动生成 datagridview 代码的 CCCustomers.designer.cs 文件来确认这一点.

Your datagridview is private to the user control. You can confirm this by inspecting the CCCustomers.designer.cs file where the code for your datagridview is auto-generated.

填充数据源的正确方法是在用户控件上创建一个公共方法,例如

The correct way to populate the datasource is to create a public method on your usercontrol eg

public void LoadData(List<Customer> customers)
{
    dgvCustomers.DataSource = customers;
}

您可以像这样从主表单调用:

which you would call from your main form like so:

private void Form1_Load(object sender, EventArgs e)
{
    db = new DatabaseContext();
    CCCustomers.LoadData(db.Customers.ToList());
}

这篇关于无法访问用户控制组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆