对于那里的大师来说,我在表单中传递值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();
最佳答案
UserControlA 知道/应该知道 UserControlB?
然后创建一个 UserControlB
类型的属性在UserControlA
,然后每当您想将数据传递到 UserControlB
时,使用 UserControlB
中的实例属性。
哪个是哪个?是的,也许是BindingNavigator
和BindingSource
例子更清楚一点:
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
属性。
为了更清楚一点,再次使用 BindingNavigator
和BindingSource
:
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/