2015-11-06 65 views
0

我有一個showForm按鈕編程創建並打開一個新的form2與4個DomainUpDown元件和OKBtn按鈕Form1中。我需要通過我的OKBtnform2form1 richtextbox將DomainUpDown元素的值傳遞給我。我唯一的區別在於最後的問號。以下是代碼片段:從程序生成形式傳遞DomainUpDown.Value到主要形式

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, ? "); 
} 
+0

您需要將'marginRightVal'變量聲明移到該方法的外部,以便您還可以在OKBtn_Click事件處理函數中使用它。或者使用lambda表達式。 –

回答

1

您可以按照漢斯順便他的建議,或者你可以投單擊事件的sender到控制,到形式的引用,並遍歷Controls收集找到控制您正在尋找。一旦找到,將其分配給一個變量並在邏輯中使用它。一個implentation看起來是這樣的:

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 
} 
+0

謝謝@rene!它幫助了很多!現在我必須再添加3個DomainUpDowns,但我想我已經明白了! –