以编程方式增加对象名称C#

时间:2016-08-04 08:43:08

标签: c# object textbox names

我有一个用于数据输入的文本框和10个用于显示数据的文本框。默认情况下,10个查看器文本框为visible=false。例如,当我输入文本框计数为“3”时,只能看到3个文本框。 (然后我可以用这些文本框做任何我想做的事情)

Example

这是我的代码;

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());

SqlCommand pencere = new SqlCommand("select COUNT (distinct(grup)) as ürün from fiyat", conn);
SqlCommand pencereisimleri = new SqlCommand("select distinct(grup) as ürün from fiyat", conn);
conn.Open();
SqlDataReader dr = pencere.ExecuteReader();
SqlDataAdapter da = new SqlDataAdapter(pencereisimleri);
DataTable dt1 = new DataTable();
da.Fill(dt1);

List<String> stringArr = new List<String>();

for (int a = 0; a < dt1.Rows.Count; a++)
{
    TextBox[a].Visible = true;
    TextBox[a].Text = "Open Textbox";                    
}

3 个答案:

答案 0 :(得分:1)

不确定,如果您要这样做,但是如何将文本框添加到集合中,如数组或列表?

示例:

private List<TextBox> boxes = new List<TextBox>();
boxes.Add(textBox1);
boxes.Add(textBox2);
// etc...

然后你可以使用foreach(或for)循环来浏览你的框:

for (int a = 0; a < dt1.Rows.Count; a++)
{
    boxes[a].Visible = true;
    boxes[a].Text = "Open Textbox";
}

答案 1 :(得分:0)

int count = dt1.Rows.Count;

foreach (Control x in this.Controls)
{
    if (count == 0)
       break;

    if (x is TextBox)
    {
        ((TextBox)x).Text = "Open Textbox";
        ((TextBox)x).Visible = true;
        count--;
    }
}

答案 2 :(得分:0)

您可以将可见性绑定到数组

Visibility[] tbViz = new Visibility[10];
public Visibility[] TbViz { get { return tbViz; } }
public void UpdateViz(int num)
{
    for (int i = 0; i < tbViz.Length; i++)
    {
        if (i < num)
            tbViz[i] = System.Windows.Visibility.Visible;
        else
            tbViz[i] = System.Windows.Visibility.Hidden;
    }

}

Visisbility="{binding path=TbViz[0]}" 

如果winforms相同的方法

public void UpdateViz(int num)
{
    for (int i = 0; i < tbViz.Length; i++)
        tbViz[i].Visisble = (i < num);
}