我有一个带有showForm
按钮的form1,该按钮以编程方式创建并打开一个包含4个form2
元素和DomainUpDown
按钮的新OKBtn
。我需要使用DomainUpDown
OKBtn
从form2
到form1
richtextbox传递public void showForm_Click(object sender,EventArgs e)
{
Form frm = new Form();
frm.Size = new Size(264, 183);
frm.Name = "MarginSelector";
frm.Text = "Qiymət ver";
frm.ShowIcon = false;
frm.Show();
DomainUpDown marginRightVal = new DomainUpDown();
marginRightVal.Location = new Point(150, 100);
marginRightVal.Size = new Size(42, 40);
frm.Controls.Add(marginRightVal);
for (int i = 0; i < 100; i++)
{
marginRightVal.Items.Add(i + "%");
}
Button OKBtn = new Button();
OKBtn.Visible = true;
OKBtn.Text = "OK";
OKBtn.Size = new Size(30, 23);
OKBtn.Location = new Point(96, 109);
frm.Controls.Add(OKBtn);
OKBtn.Click += new System.EventHandler(this.OKBtn_Click);
}
public void OKBtn_Click(object sender, EventArgs e)
{
textArea.SelectionLength = 0;
textArea.SelectedText = string.Filter("margin-top: {0} ; \n, ? ");
}
元素的值。我只有diffulty是最后的问号。以下是代码段:
<pre>Tid = {{(p.tempo*p.distanse)*60000 | date: "HH't' mm'min' ss'sek'"}}</pre>
答案 0 :(得分:1)
您可以关注Hans Passant他的建议,或者您可以将点击事件的sender
投射到控件,获取对表单的引用并迭代Controls
集合以找到您的控件&# 39;重新寻找。找到后,将其分配给变量并在逻辑中使用它。实现可能如下所示:
public void OKBtn_Click(object sender, EventArgs e)
{
// assume a Control is the sender
var ctrl = (Control)sender;
// on which form is the control?
var frm = ctrl.FindForm();
// iterate over all controls
DomainUpDown domainUpDown = null;
foreach(var ctr in frm.Controls)
{
// check if this is the correct control
if (ctr is DomainUpDown)
{
// store it's reference
domainUpDown = (DomainUpDown)ctr;
break;
}
}
// if we have found the control
if (domainUpDown != null)
{
textArea.SelectionLength = 0;
Debug.WriteLine(domainUpDown.SelectedIndex);
Debug.WriteLine(domainUpDown.SelectedItem);
// use the SelectedItem
textArea.SelectedText = string.Format("margin-top: {0} ; \n,", domainUpDown.SelectedItem );
}
}
如果表单上有多个控件,最好为每个控件添加一个唯一的名称:
DomainUpDown marginRightVal = new DomainUpDown();
marginRightVal.Location = new Point(150, 100);
marginRightVal.Size = new Size(42, 40);
marginRightVal.Name = "right";
frm.Controls.Add(marginRightVal);
当您遍历控件集合时,您可以检查该名称:
foreach(var ctr in frm.Controls)
{
// check if this is the correct control
if (ctr is DomainUpDown)
{
// store it's reference
domainUpDown = (DomainUpDown)ctr;
if (domainUpDown.Name == "right")
{
// do logic for that value
}
}
}
或者您可以使用Find method:
var found = frm.Controls.Find("right", false);
if (found.Length>0)
{
var rightDomain = (DomainUpDown)found[0];
// do logic here
}