简体   繁体   English

我可以遍历TextBox ID来检查/更改ASP.NET C#中的值吗?

[英]Can I loop through TextBox id's to check / change values in asp.net c#?

I'm working on a project and I'm a beginner and I'm having a little trouble with this. 我正在从事一个项目,并且是一个初学者,对此有点麻烦。 I'm trying to check if a textbox is empty and if it is to change the value to N/A so that I can input n/a into a database instead of it not working. 我正在尝试检查文本框是否为空,以及是否要将值更改为N / A,以便可以将n / a输入数据库而不是不起作用。

Here is the code that I thought would work but didn't because the .Text property isn't near the ID anymore: 这是我认为可以使用的代码,但是由于.Text属性不再位于ID附近而无法使用:

for(int i = 1; i<=17; i++)
{
if(!("tb" + i).Text)
"tb" + i.Text = "n/a";
}

I wasn't sure if the true/false would work but I never got to find out because it doesn't compile to begin with. 我不确定对/错是否会奏效,但我从来没有发现,因为它不能一开始就编译。 I have 17 textboxes on my design page all with ID 'tb + i' eg tb1, tb2 我的设计页面上有17个文本框,都带有ID'tb + i',例如tb1,tb2

thx 谢谢

If you want to loop through the textbox ids, you have to find the control on the page first using the FindControl method. 如果要遍历文本框ID,则必须首先使用FindControl方法在页面上找到控件。

Then you can create your loop like this: 然后,您可以像这样创建循环:

TextBox txt;
for(int i = 1; i<=17; i++)
{
    txt = (TextBox)Page.FindControl("tb" + i);
    if(string.IsNullOrEmpty(txt.Text))
        txt.Text = "n/a";
}

You can use FindControl method 您可以使用FindControl方法

for(int i = 1; i<=17; i++)
{
    var textBox = Page.FindControl("tb" + i) as TextBox;

    if(textBox != null && textBox.Text == "") { ... }
}

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

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