0

I am trying to make a button inside a webform visible if data available. I have a database with a column name NCID, then in a views I count the NCID's. and I a have btn1 till btn9 hidden. If NCID Count is 1 show button btn1, if NCID Count is 2 then show btn1 and btn2.

How can I target the Button ID to make it visible or hide it?

I tried the following but it is not working for me.

while (sr.Read())
{
    string NCID = sr["NCID"].ToString();
    int nc2 = Convert.ToInt32(NCID);
    int x = 1;

    do
    {
        string btnx = "btn" + x;
        btnx.Visible = true;

        x++;
    } while (x <= nc2);
}

con.Close();
Steve
  • 2,988
  • 2
  • 30
  • 47

2 Answers2

1

If this is a Windows Forms app, you can use:

Controls.Find(btnx, true).First().Visible = true;

Find control by name from Windows Forms controls

https://msdn.microsoft.com/en-us/library/system.windows.forms.control.controlcollection.find(v=vs.110).aspx

If it's WebForms, you can use:

FindControl(btnx).Visible = true;

https://msdn.microsoft.com/en-us/library/486wc64h(v=vs.110).aspx

Jared
  • 1,385
  • 11
  • 21
  • I tried Controls.FindControl(btnx).Visible = true; then I get an error "ControlCollection does not contain a definition for FindControl" – Hemin T Aug 07 '17 at 14:30
  • Can you update your question to show how you're declaring controls in HTML? – Jared Aug 07 '17 at 15:14
  • string NCID = sr["NCID"].ToString(); int nc2 = Convert.ToInt32(NCID); int x = 1; do { string btnx = "btn" + x; Controls.FindControl(btnx).Visible = true; x++; } while (x <= nc2); – Hemin T Aug 08 '17 at 09:31
  • Sorry, it's been a while since I did WebForms. I updated the answer to show you can just use FindControl, not Controls.FindControl, after confirming this works in an old WebForms project. – Jared Aug 08 '17 at 14:20
0

(see jareds answer)

for (int i = 0; i < x; i++) //smaller then ammount of lines returned      
{
  Controls.Find(btnx + i).Visible = true; //add visibility to wichever control (found by name) you wanted to add
}
Louis-Roch Tessier
  • 822
  • 1
  • 13
  • 25
Freek W.
  • 406
  • 5
  • 20