Friday, February 4, 2011

How To set Dynamic control names - fill controls in loop c#

# Syntax (Toggle Plain Text)


      using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.Data;
      using System.Drawing;
      using System.Linq;
      using System.Text;
      using System.Windows.Forms;

      namespace daniweb

      {

      public partial class frmFindControl : Form

      {

      private List<ArticlePrice> prices;
      public frmFindControl()

      {

      InitializeComponent();

      //initialize the list

      prices = new List<ArticlePrice>();

      for (int i1 = 1; i1 <= 3; i1++)

      {

      prices.Add(new ArticlePrice(i1));

      }

      }

      private void button1_Click(object sender, EventArgs e)

      {

      const string textBoxBaseName = @"textBox";

      if (prices.Count > 0)

      {

      //repeat until we used 10 text boxes or the list ran out of elements

      for (int i1 = 1; i1 <= Math.Min(prices.Count, 10); i1++)

      {

      string ctrlName = textBoxBaseName + i1.ToString("F0");

      TextBox tb = null;

      //Find the controls and search all child containers. Should return 1 element

      Control[] ctrls = this.Controls.Find(ctrlName, true);

      //Make sure it was found

      if ((ctrls.Length > 0) && (ctrls[0] is TextBox))

      tb = (ctrls[0] as TextBox);

      //We didnt find it

      if (tb == null)

      throw new Exception(string.Format("Could not locate text box '{0}'!", ctrlName));

      //We did find it, set the price

      tb.Text = prices[i1-1].Price.ToString("F2");

      }

      }

      }    

      }

      //I mocked up a class since you didnt post your code

      public class ArticlePrice

      {

      public decimal Price { get; set; }

      public ArticlePrice()

      {

      this.Price = default(decimal);

      }

      public ArticlePrice(decimal Price)

      : this()

      {

      this.Price = Price;

      }

     }

      }