How to get Text from Textbox created during runtime

后端 未结 2 2040
执念已碎
执念已碎 2021-01-25 18:09

I have created WinForm App in which user can set how many textboxes he want (Range 1-99) I am using this code to create Textboxes during runtime

  for (int i = 0         


        
相关标签:
2条回答
  • 2021-01-25 19:00

    This may work, I built a separate class to store the control and its value, then you can work out the values independently from the rest of the form. You need to trigger the calculations though:

        private List<InfoTextBox> activeTextBoxes = new List<InfoTextBox>();
        public Form1()
        {         
            for (int i = 0; i < Calculation.Num; i++)
            {
                TextBox txtRun = new TextBox();
                txtRun.Name = "txtBox" + i;
                txtRun.Location = new System.Drawing.Point(35, 50 + (20 * i) * 2);
                txtRun.Size = new System.Drawing.Size(75, 25);
                this.Controls.Add(txtRun);
                InfoTextBox iBox = new InfoTextBox();
                iBox.textbox = txtRun;
                activeTextBoxes.Add(iBox);
            }
        }
    
        public class InfoTextBox
    {
        private double _textboxValue;
        public TextBox textbox { get; set; }
        public double TextBoxValue { get { return _textboxValue; } set { _textboxValue = setValue(value); } }
    
        private double setValue(double invalue)
        {
            return invalue / 100;
        }
    }
    
    0 讨论(0)
  • 2021-01-25 19:13
    var sum = this.Controls.OfType<TextBox>()
        .Where(t => char.IsDigit(t.Name.Reverse().Take(1).FirstOrDefault())
            && t.Enabled)
        .Select(t =>
        {
            double i;
            if (!double.TryParse(t.Text, out i)) { return 0d; }
            return i / 100d;
        })
        .Sum();
    
    0 讨论(0)
提交回复
热议问题