简体   繁体   English

c# 循环 10000 个文本框而不写其名称

[英]c# Loop 10000 textboxes without writing their name

Example:例子:
I have 1000 textboxes in 1 form.我有 1000 个文本框,有 1 种形式。 The textboxes names are textbox1, textbox2... textbox1000 I want to be able to do the following thing:文本框名称是 textbox1, textbox2... textbox1000 我希望能够执行以下操作:

String myString = "textbox";
for (int i = 0; i <= 1000; i = i + 1) 
myString + i.Text = "Textbox number " + i.ToString() 
next

IMPORTANT, solve my goal not my example重要,解决我的目标不是我的榜样

My goal is to not write the textbox, and get it from a predefined string, well, like the example我的目标是不编写文本框,而是从预定义的字符串中获取它,就像示例

Sorry for the confusion and the edits.很抱歉造成混乱和编辑。 Its my first post:/这是我的第一篇文章:/

example 2, goal is the same例2,目标相同

This is case sensitive and assumes the control is on the form, not say a panel这是区分大小写的,并假定控件在表单上,而不是面板上

string txt1 = "textBox1";
var textbox = Controls.OfType<TextBox>().FirstOrDefault(x => x.Name == txt1);
if (textbox != null)
{
    textbox.Text = "";
}

In a panel or group-box在面板或组框中

var tb = Controls.Find(txt1, true);
if (tb.Length >0)
{
    ((TextBox)tb[0]).Text = "";
}

Then for 1-1000然后为 1-1000

for (int index = 0; index < 1000; index++)
{
    var textbox = Controls.OfType<TextBox>().FirstOrDefault(x => x.Name == $"textBox{index}");
    if (textbox != null)
    {
        textbox.Text = "";
    }
}

Edit编辑

var baseText = "Textbox number ";
for (int index = 0; index < 1000; index++)
{
    var textBox = Controls.OfType<TextBox>().FirstOrDefault(x => x.Name == $"textBox{index}");
    if (textBox != null)
    {
        textBox.Text = $"{baseText}{index}";
    }
}

I believe you want to edit the text in a Textbox.我相信您想在文本框中编辑文本。 You can do like so:你可以这样做:

string txt1 = Textbox1.Text;
txt1 = "(Edited Text)" + txt1;

And to change the text of Textbox at runtime, you can set the Text property of Textbox to that string.要在运行时更改 Textbox 的文本,您可以将 Textbox 的 Text 属性设置为该字符串。

Textbox1.Text = txt1;

Complete code, will then be:完整的代码,将是:

string txt1 = Textbox1.Text;
txt1 = "(Edited Text)" + txt1;
Textbox1.Text = txt1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM