c# - C# UserControl 取决于它所在的表单 - WinForms
问题描述
我有如下问题,
我需要创建UserControl
以不同形式放置的。但它的行为取决于它所处的形式。
示例:
Form1
具有从 db 获取数据并将其发送到我的按钮UserControl
。然后它创建假设另一个可以单击的控件,但是单击时它会调用 db(取决于Form1
)并在下面创建新控件。
Form2
执行相同但不同的数据库调用。
我的问题是如何调用第二个调用UserControl
- 当它依赖于使用的外部表单时如何对数据库进行查询?
解决方案
这听起来像是一个绝对可怕的设计,但这就是你的做法:
private void button1_Click(object sender, EventArgs e)
{
if (this.ParentForm != null)
{
if (this.ParentForm is Form1)
{
Form1 f1 = (Form1)this.ParentForm; // if you need a reference to the Form1 instance
// ... do stuff for Form1 ...
}
else if (this.ParentForm is Form2)
{
Form2 f2 = (Form2)this.ParentForm; // if you need a reference to the Form2 instance
// ... do stuff for Form2 ...
}
else if (...)
{
}
}
}
推荐阅读
- c# - 将 PropertyGroup 添加到 csProj C#
- javascript - 如何从文档和窗口中删除 JavaScript 触摸事件处理程序?
- python - 如何实时获取 QLineEdit 文本光标位置
- pandas - value_counts 并按组归一化
- sql - 返回 FieldValue 其中 FieldName 等于 Value 并且 ID 等于 Number
- python - QPainterPath 沿多条路径绘制和放置项目
- firebase - 使用 Firebase 的实时数据库的安全性最佳实践?
- c - 父指针更改时子指针段错误
- php - 使用类似于 dompdf 的库导出渲染 php 5.1
- reactjs - 同步操作之后的线路会立即注意到更改吗?