1

In classic ASP i could do this when looping throu a unknown inputfields:

<input id="textbox1" type="text">
<input id="textbox2" type="text">
<input id="textbox3" type="text">
<input id="textbox4" type="text">
<input id="textbox5" type="text">   

For i = 1 To 5  

   strTextbox = request.form("textbox" & i)

   If strTextbox <> "" Then 
    // Do the magic!
   End If

Next

With this the user could input values to textbox 1, 3, 4 and 5 or maybe only 1 and 2 and i could collect the values inputs in the For loop.

How could i do this in C#?

I cant do this because it dosent like that i add a i in the middle om my textbox.Text;

for (int i = 1; i < 6; i++)
{
   strTextbox = textbox[i].Text; 

   if (!string.IsNullOrEmpty(strTextbox)
   {
     // Do the magic!
   }
}

I now have a lot of if:s checking every textbox inside the loop but it got to be a easyer way?

Slint
  • 355
  • 1
  • 4
  • 17

2 Answers2

2

You can use FindControl on the NamingContainer of your textboxes.

If they're are on top of the page and not nested in other controls like GridView:

for (int i = 1; i < 6; i++)
{
   string strTextbox = "textbox" + i.ToString();
   TextBox txt = this.FindControl(strTextbox) as TextBox;
   if (txt != null && !string.IsNullOrEmpty(txt.Text))
   {
      // ... 
   }
}

But i would use more meaningful names instead.


I want access to the textboxes from a button_click event only on the actual page. The controls are inside a panel.

Then i would use this LINQ approach:

List<TextBox> filledArticleTBS = txtPanel.Controls.OfType<TextBox>()
    .Where(txt => txt.ID.StartsWith("textbox") && !String.IsNullOrEmpty(txt.Text)) 
    .ToList();
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Perhaps add something like ` && txt.Text != String.Empty` to the if clause. Although that could of course be left as an exercise for the OP... – user1429080 May 30 '16 at 11:34
  • Ok, looks like it would work. I tried to implement this but i'm unable to get the values from the textboxes and i guess that it is due to that i have nested masterpages!..?! I'm using asp:textboxes and have tried to use findcontrol like this: TextBox txt = this.Master.Master.FindControl(strTextbox) as TextBox; txt apears as null when debugging even thou it contains text. I've also tried to use this: TextBox txt = this.FindControl(strTextbox) as TextBox; and finaly also tried this: strTextbox = "MainContent_MainContent_textbox" + i.ToString(); with no luck. :( – Slint May 30 '16 at 14:25
  • @Slint: you should really consider to use a more solid approach. Why don't you provide meaningful names to the textboxes and access them directly? You should at least put them in the same container-control. Where are they? From where do you want to access them? We have to know this to provide the best answer. Until then you could use [this](http://stackoverflow.com/a/4955836/284240) recursive `FindControl`, although i would strongly advise against it since it's not just inefficient but prone to errors. What if you have multiple controls with the same ID in different naming-containers?! – Tim Schmelter May 30 '16 at 14:33
  • The whole thing is for batch inventory. So the user scans barcode that finds articles whit the help of som Ajax and jQuery. When the article is found it replaces the barcode number in the textbox with the actual article number and then moves to the next textbox. I never know what article is going to be scanned or how many. I have 20 textboxes named ArticleNr1 to 20 sometimes the user scan 1 article and sometimes it might be 4 or 18 etc. Today i solve it by using if (!string.IsNullOrEmpty(ArticleNr1)) and the same for article 2,3,4... and loop that 20 times but it dosent feel efficient. – Slint May 30 '16 at 15:31
  • My textboxes with those names only resides in the specific page. – Slint May 30 '16 at 15:32
  • I want access to the textboxes from a button_click event only on the actual page. The controls are inside a panel. – Slint May 30 '16 at 16:00
  • @Slint: then i would use an approach like the one i've added to my answer – Tim Schmelter May 31 '16 at 07:36
0

I did manage to get this working with some extra lines.

So the final code was to first find Contentplaceholder in my top master, then search for the Contentplaceholder in my nested Masterpage and finaly search for the textbox. It works, but when debugging i can see that there are some other isues with the code where in some cases the textbox is'nt found. I'm going back to my previusly working code where i access all the controls directly and not with findcontrol. But if someone is intrested this worked (almost) for me:

My Top Masterpage (Site.Master)

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="mysite.SiteMaster" %>
<html>
<head>
    // MasterPage head stuff
    // ...
</head>
<body>
<asp:ContentPlaceHolder ID="MainContent" runat="server">
    // My contentpages that use only the top masterpage
    // My contentpage contacts.aspx begin here, This is in a separate file called contacts.aspx. 
    // In code the contentpage is theoretically here, when the site runns it works in another way. Here things are explained; http://odetocode.com/articles/450.aspx
    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="contacts.aspx.cs" Inherits="mysite.contacts" %>
    <asp:Content ID="contactsContent" ContentPlaceHolderID="MainContent" runat="server">
        // Here is the content of a contentpage (contacts.aspx) that use the Site.Master
    </asp:Content>
    // contentpage contacts.aspx end here
</asp:ContentPlaceHolder>
</body>
</html>

My Nested Masterpage (XYZ.master)

<%@ Master Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="XYZMasterPage.master.cs" Inherits="mysite.XYZ.XYZMasterPage" %>
<asp:Content ID="NestedMasterPageContentPlaceHolder" ContentPlaceHolderID="MainContent" runat="server">
Nested MasterPage stuff
...
<asp:ContentPlaceHolder ID="NestedMainContent" runat="server">
    // Here is my contentpage where textbox1, 2, 3 etc. is
    // Here is the content of a contentpage (batch.aspx) that use the nested masterpage XYZMasterPage.master
    <%@ Page Title="" Language="C#" MasterPageFile="~/XYZMasterPage.master" AutoEventWireup="true" CodeBehind="batch.aspx.cs" Inherits="mysite.XYZ.batch" %>
    <asp:Content ID="batchInvContent" ContentPlaceHolderID="NestedMainContent" runat="server">
      // Here is the content of a contentpage (batch.aspx)
      <asp:Panel ID="PanelBatch" Runat="Server" >
        <asp:TextBox runat="server" ID="ArticleNr1" />
        <asp:TextBox runat="server" ID="ArticleNr2" />
        <asp:TextBox runat="server" ID="ArticleNr3" />
        <asp:TextBox runat="server" ID="ArticleNr4" />
        <asp:TextBox runat="server" ID="ArticleNr5" />  
        <asp:Button runat="server" ID="buttSubmit" OnClick="buttSubmit_Click" />    
      </asp:Panel>
    </asp:Content>      
    // contentpage batch.aspx end here
</asp:ContentPlaceHolder>

My codebehindfile for batch.aspx

protected void buttSubmit_Click(object sender, EventArgs e)
{
    ContentPlaceHolder parentCP = this.Master.Master.FindControl("MainContent") as ContentPlaceHolder;
    ContentPlaceHolder childCP = parentCP.FindControl("NestedMainContent") as ContentPlaceHolder;

    string strTextbox = string.Empty;                

    for (int i = 1; i < 6; i++)
    {
       strTextbox = "ArticleNr" + i.ToString();
       TextBox txt = childCP.FindControl(strTextbox) as TextBox;
       if (txt != null && !string.IsNullOrEmpty(txt.Text))
       {
          // ... 
          // Insert to db
          // ...
       }
    }
}
Slint
  • 355
  • 1
  • 4
  • 17
  • Too complicated and error-prone ;-) You don't need the `FindControl` approach if you want to access the textboxes in the panel from `buttSubmit_Click`, just `PanelBatch.Controls.OfType()` – Tim Schmelter May 31 '16 at 08:48