我正在尝试创建一个新的用户控件作为通用查找表单开头。
lkpControl.FormToOpen="FrmProductList";
lkpControl.ReturnValueVariableName="ProductCode";
lkpControl.ShowThatForm();
if dialog result is OK:
lkpControl.txtValue=lkpControl.GetSelectedValue();
此控件将从其名称中打开预配置(或在设计时指定)表单,并将打开表单中的所选项目返回其文本框。就像从文件夹浏览器对话框中获取路径一样。
只是打开表单中所选项目的通用表单开头和值getter。
如果您能指导我找到任何解决方案或要遵循的路径,我将不胜感激。
提前致谢
更新: 我已经解决了这个问题:
public partial class LookupButton : UserControl
{
[Description("Type of the Form To Open: typeof(LookupButtonTest.Form2)")]
[Category("Custom")]
public Type FormToOpen { get; set; }
[Description("Name Of the public property to get return value from opened form.")]
[Category("Custom")]
public string PropertyToGet { get; set; }
public LookupButton()
{
InitializeComponent();
}
private void btnOpenForm_Click(object sender, EventArgs e)
{
if (FormToOpen == null)
{
throw new ArgumentNullException("FormToOpen");
}
if (PropertyToGet.Length <= 0)
{
throw new ArgumentNullException("PropertyToGet");
}
Form objForm = (Form)Activator.CreateInstance(FormToOpen);
if (objForm.ShowDialog() == DialogResult.OK)
{
bool propertyFound = false;
PropertyInfo[] props = objForm.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (PropertyInfo p in props)
{
if (p.Name == PropertyToGet)
{
txtReturnVal.Text = p.GetValue(objForm, null).ToString();
propertyFound = true;
}
}
if (!propertyFound)
{
throw new ArgumentNullException("PropertyToGet");
}
}
}
}
答案 0 :(得分:0)
这样的事情:
public static class ShowFormAs
{
public static T1 ShowForm<T1>(string fullTypeName, string propertyName)
where T1: class
{
return string.IsNullOrEmpty(fullTypeName)
? default(T1) :
ShowForm<T1>(System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(fullTypeName) as Form, propertyName);
}
public static T1 ShowForm<T, T1>(string propertyName)
where T: Form, new ()
where T1: class
{
return ShowForm<T1>(new T(), propertyName);
}
private static T1 ShowForm<T1>(Form form, string propertyName)
where T1: class
{
if (form == null)
{
return default(T1);
}
if (form.ShowDialog() == DialogResult.OK)
{
var property = form.GetType().GetProperties().FirstOrDefault(o => string.CompareOrdinal(o.Name, propertyName) == 0);
if (property == null)
{
return default(T1);
}
return property.GetValue(form, null) as T1;
}
return default(T1);
}
}
用法:
var x = ShowFormAs.ShowForm<Form2, string>("TTT");
var z = ShowFormAs.ShowForm<string>("StackOverflow.Form2", "TTT");
Form2类是:
namespace StackOverflow
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string TTT { get { return "Ololo"; } }
}
}
结果是: