PDA

View Full Version : سوال: دسترسی به متغیر خصوصی داینامیک



aliwishstar
سه شنبه 18 تیر 1392, 20:35 عصر
با سلام خدمت همه دوستان و اساتید.
من قطعه کدی را به صورت زیر نوشتم.حالا نیاز دارم که در button2_Click به آرایه textbox که به صورت داینامیک ساخته می شود(txt[i]) به محتویات آن دسترسی داشته باشم.
لطفا راهنمایی کنید.مرسی



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 WindowsFormsApplication21
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int c = 0;
int x = 20;
private void button1_Click(object sender, EventArgs e)
{
string s = textBox1.Text;

foreach (char z in s)
{
c = c + 1;
}
TextBox [] txt=new TextBox [c];

for (int i = 0; i < c; i++)
{
txt[i] = new TextBox();
txt[i].Location = new Point(x, 20);
txt[i].Width = 50;
txt[i].Height = 30;
txt[i].Text = s[i].ToString();
this.Controls.Add(txt[i]);
x = x + 70;
}
}

private void button2_Click(object sender, EventArgs e)
{

}
}
}

CsharpNevisi
سه شنبه 18 تیر 1392, 20:46 عصر
سلام .... !!!
بیا این کدو زیر بنویس
int x = 20;
TextBox[] txt;

بعد جای این
TextBox [] txt=new TextBox [c];
اینو بنویس
txt=new TextBox [c];
بعدش تو هرجا از کلاس فرم جاری خواستی میتونی بهش دسترسی داشته باشی
MessageBox.Show(txt[i].Text);
i هم که خودت میدونی دیگه یه عددی برای ایندس تکت باکسه

uthman
سه شنبه 18 تیر 1392, 20:57 عصر
int c = 0;
int x = 20;
List<TextBox> myarr = new List<TextBox>();
private void button1_Click(object sender, EventArgs e)
{
string s = textBox1.Text.Length.ToString() ;

c = Convert.ToInt32(s);
TextBox[] txt = new TextBox[c];

myarr.Add(textBox1);
Array d = myarr.ToArray();

myarr.ToArray();



for (int i = 0; i < c; i++)
{
myarr.Add(textBox1);
myarr[i] = new TextBox();
myarr[i].Location = new Point(x,20);

myarr[i].Width = 50;
myarr[i].Height = 30;

this.Controls.Add(myarr[i]);

x = x + 70;
}
}

private void button2_Click(object sender, EventArgs e)
{
myarr[0].Text = "Osman";
}


سلام دوست من.از ژنریک ها استفاده کردم.

مهرداد صفا
چهارشنبه 19 تیر 1392, 13:27 عصر
با سلام.
در هنگام ایجاد کنترلها مقدار خصوصیت Name آنها را Set کنید تا با استفاده از Form.Controls به آنها دسترسی داشته باشید:

namespace WindowsFormsApplication21
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int c = 0;
int x = 20;
private void button1_Click(object sender, EventArgs e)
{
string s = textBox1.Text;

foreach (char z in s)
{
c = c + 1;
}
TextBox [] txt=new TextBox [c];

for (int i = 0; i < c; i++)
{
txt[i] = new TextBox();
//remember to do this
txt[i].Name="txt"+i.ToString()
txt[i].Location = new Point(x, 20);
txt[i].Width = 50;
txt[i].Height = 30;
txt[i].Text = s[i].ToString();
this.Controls.Add(txt[i]);
x = x + 70;
}
}

private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show((this.Controls["txt1"] as TextBox).Text);
}
}
}