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();
6
  • Is this webforms, mvc, wpf? Commented Aug 7, 2017 at 13:34
  • I tried the following but it is not working for me!! Define not working. What did you expect to happen? What actually happened? Commented Aug 7, 2017 at 13:35
  • sorry, it is a webform Commented Aug 7, 2017 at 13:35
  • See : msdn.microsoft.com/en-us/library/486wc64h(v=vs.110).aspx Commented Aug 7, 2017 at 13:37
  • By not working I mean the button remain hidden. Commented Aug 7, 2017 at 13:38

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

I tried Controls.FindControl(btnx).Visible = true; then I get an error "ControlCollection does not contain a definition for FindControl"
Can you update your question to show how you're declaring controls in HTML?
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);
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.
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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.