c# - 在表单中将数据从用户控件 A 传递到用户控件 B

标签 c# .net winforms user-controls

对于那里的大师来说,我在表单中传递值2个用户控件时遇到问题。我有用户控件 A,它有组合框和一个按钮,控件 B 有一个 datagridview。现在我想显示 datagridview 中的用户控件 B 中的数据。如何将数据从 UCA 传递到 UCB? 这是我要传递的数据:

因此,在用户控件 A 中,当我单击名为“生成”的按钮时,它将使用下面的 GetConvo() 中生成的数据填充用户控件 B 中的 datagridview。

public DataTable GetConvo() {
    DataTable table = new DataTable();
    table.Columns.Add("ConvoUser", typeof(Object));
    table.Columns.Add("Message", typeof(Object));
    table.Columns.Add("Date", typeof(Object));

    var _data = from data in User.GetMatchConvo(comboBox3.SelectedValue.ToString())
                select new {
                    convoUser = data.actor_id,
                    convoMessage = data.message,
                    convoDate = data.creation_timestamp
                };
    foreach (var data in _data) {
        table.Rows.Add(data.convoUser, data.convoMessage, data.convoDate);
    }

    //dataGridView1.AllowUserToAddRows = false;
    //dataGridView1.AllowUserToDeleteRows = false;
    return table;
}

private UserInterface User = new UserData();

enter image description here

最佳答案

UserControlA 知道/应该知道 UserControlB?

然后创建一个 UserControlB 类型的属性在UserControlA ,然后每当您想将数据传递到 UserControlB 时,使用 UserControlB 中的实例属性。

哪个是哪个?是的,也许是BindingNavigatorBindingSource例子更清楚一点:

public class BindingNavigator
{
    Public BindingSource BindingSource { get; set; }
    public int Position
    {
        get {return BindingSource?.Position ?? -1};
        set {if(BindingSource!=null) BindingSource.Position = value;}
    }
}

然后当您删除 BindingNavigator 的实例时和 BindingSource 的一个实例在表单上设置BindingSource BindingNavigator的属性(property)至bindingSource1 .

UserControlA 不/不应该认识 UserControlB?

使用事件。这是最自然的方式。你每天都在使用它,比如TextChanged , SelectedIndexChanged , 等等。是时候为您的用户控件创建一个了。

事实上,您需要在 UserControlA 中引发事件,然后在表单上,​​当您删除 UserControlA 的实例时和 UserComtrolB 的实例, handle UserControlA事件和设置UserControlB属性。

为了更清楚一点,再次使用 BindingNavigatorBindingSource :

public class BindingNavigator
{
    public event EventHanlder MovingNext;
    public void MoveToNextRecord()
    {
        MovingNext?.Invoke(this, EventArgs.Empty);
    }
}

然后当您删除 BindingNavigator 的实例时和 BindingSource 的一个实例在表单上,​​处理 MovingNext事件bindingNavigator1并设置 bindingSource1 的位置:

bindingNavigator1.MovingNext += (obj, args) => {
    bindingSource1.Position +=1;
};

想要了解有关事件的更多信息吗?查看以下文档:

关于c# - 在表单中将数据从用户控件 A 传递到用户控件 B,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60081321/

相关文章:

.net - 我可以在项目/解决方案级别上设置Option Explicit和Option Strict吗?

c# - 调整 FlowLayoutPanel 中用户控件之间的间距

c# - 禁用 GeckoFX 确认消息

c# - 安装在另一台计算机上时 UI 会更改大小

c# - 如何处理 WCF 上的故障状态? (在 Windows 服务中托管)

c# - Discord.net bot 嵌入消息

c# - 属性总是不可变的吗?

c# - 在 SQL 中参数化 'order by'

c# - 在 WPF 中放入像 Html Float Resource 这样的图片

c# - 如何建立一个网址?