TextBox Visible attribute - c#

I am currently working with visible attributes on textboxes. Below I copy pasted a snippet of my code. I have several textboxes in my form. It is going to become very tedious trying to write it as I have below for all the textboxes. Is there a way to compress my code to a few lines to make the textboxes visible?
public void makeVisible()
{
textBox1.Visible = true;
textBox2.Visible = true;
textBox3.Visible = true;
textBox4.Visible = true;
//etc.
}

Try this:
foreach(Control c in Controls)
{
TextBox tb = c as TextBox;
if (tb !=null) tb.Visible = false; //or true, whatever.
}
For limited textboxes:
int count = 0;
int txtBoxVisible = 4;
foreach(Control c in Controls)
{
if(count <= txtBoxVisible)
{
TextBox tb = c as TextBox;
if (tb !=null) tb.Visible = false; //or true, whatever.
count++;
}
}
You can set txtBoxVisible according to your need.

Put the textboxes in an array and loop through the array or
put the textboxes in a panel, grid, group, ... and change the visibility of that container.

Use something similar to the following:
foreach (TextBox textBox in container.Controls.Cast<Control>().OfType<TextBox>())
{
textBox.Visible = value;
}
Refer to the following:
LINQ (Language-Integrated Query)
Enumerable.Cast Method
Enumerable.OfType Method

Related

How to check if a GridView contains a certain Button asp.net c#

hi i would like to know how can i check if any of the reviewBtn is visible in the gridview and if ANY reviewBtn is present, btn_reviewAll will be visible.
currently the code below only shows the btn_reviewAll when ALL reviewBtn is visible. pls advise thanks!
foreach (GridViewRow row in GridViewReview.Rows)
{
Control reviewBtn = row.FindControl("ButtonReview") as Button;
if (reviewBtn.Visible == true)
{
btn_reviewAll.Visible = true;
}
else
{
btn_reviewAll.Visible = false;
}
}
change your code like this
foreach (GridViewRow row in GridViewReview.Rows)
{
Control reviewBtn = row.FindControl("ButtonReview") as Button;
if (reviewBtn.Visible == true)
{
btn_reviewAll.Visible = true;
break;
}
else
{
btn_reviewAll.Visible = false;
}
}
what it does is when one reviewBtn is visible it will set btn_reviewAll to visible and break out the foreach loop
#Shreesha's answer is absolutely correct, you can also do with less code using LINQ like this:-
if (GridViewReview.Rows.OfType<GridViewRow>()
.Any(b => ((Button)b.FindControl("ButtonReview")).Visible))
btn_reviewAll.Visible = true;
else
btn_reviewAll.Visible = false;

Make multiple Textboxes visible or invisible using for loop

In my form I've 50 textboxes in visible=false state, when a user enter particular number , those many textboxes should be displayed and the remaining textboxes should remain in visible false state.
Should end up looking something like this:
foreach (var control in this.Controls)
{
var textbox = control as TextBox;
if (var != null) textbox.Visible = true;
}
You can loop throug all textbox controls like this:
foreach (Control item in this.form1.Controls)
{
System.Web.UI.HtmlControls.HtmlInputText tbx = item as System.Web.UI.HtmlControls.HtmlInputText;
if (tbx!= null)
{
if(tbx.Text == "some text")
tbx.Visible = false; // or true how ever you want it
else
tbx.Visible = true;
}
}
So if tbx is not null, item is textbox, actually:
<input type="text"/>
You can do this same trick with other HtmlControls.
Change form1 to that form you, which controls you want to loop through.
You can wrap all your control inside a Asp.net Panel Control.
int counter = 0;
int numberOfTextBoxtoShow = 4; // set by user
foreach (Control c in Panel1.Controls)
{
if (c is TextBox)
{
if (counter < numberOfTextBoxtoShow)
{
c.Visible = true;
counter++;
}
else c.Visible = false;
}
}

How to set value property of NumericUpDown from a string value?

I want to get values from a selected row of DataGridView and assign them into a few different
controls on a Form when a control's name match a column's name (there is TextBox, ComboBox and NumericUpDown).
This is how I am populating the controls currently:
Form myForm = new Form();
if (comboBoxTable.Text == "Client")
{
myForm = new EditClientDataWindow();
}
else if (comboBoxTable.Text == "Agency")
{
myForm = new EditAgencyDataWindow();
}
else if (comboBoxTable.Text == "Medicine")
{
myForm = new EditMedicineDataWindow();
}
string val;
foreach (Control c in myForm.Controls)
{
for (int i = 0; i < dataGridViewMDB.ColumnCount; i++)
{
val = dataGridViewMDB.SelectedRows[0].Cells[i].Value.ToString();
if (dataGridViewMDB.Columns[i].Name.ToString() ==
c.Name.ToLower().Replace(c.GetType().ToString().ToLower().Replace("system.windows.forms.", ""), ""))
{
if (c is NumericUpDown)
(c as NumericUpDown).Value = Convert.ToInt32(val);
else
c.Text = val;
}
}
}
With the exception of NumericUpDown, the other types of controls are correctly populated. For the NumericUpDown, I only ever get the default -1 value. I've also tried to use decimal.Parse() and Convert.ToDecimal() instead of Convert.ToInt32(), but there is no change in the result.
The range of NumericUpDown had been set to -1 and 999.
It's not an answer, but a way to reduce a space for error searching, because it's a lot of things going on under the hood.
Can you please change your code to
foreach (Control c in myForm.Controls)
{
if (c is NumericUpDown)
(c as NumericUpDown).Value = 12;
else
c.Text = "12";
}
After this all controls should be set to 12. Can you please test it and get back with the observations.

"Unable to cast object" while looping through programatically created textboxes

I have some Textboxes that are created dynamically --
int i = 1;
while (reader.Read())
{
System.Web.UI.WebControls.TextBox textBox = new System.Web.UI.WebControls.TextBox();
textBox.ID = reader["field_id"].ToString();
textBox.Enabled = false;
HtmlGenericControl div = new HtmlGenericControl("div");
if(i%2 != 0)
div.Attributes.Add("style", "margin-right:120px;padding-bottom:20px;");
if (i % 2 == 0)
div.Attributes.Add("style", "padding-bottom:20px;");
div.Attributes.Add("class", "inline fourcol");
div.InnerHtml = "<label>" + reader["field"] + "</label>";
div.Controls.Add(textBox);
panelId.Controls.Add(div);
textBox.Text = reader["field_value"].ToString();
++i;
}
That works fine (at least i'm sure -they show up how they should). But when i try to loop through them to enable them, or get their values, i get an "Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.TextBox'. " error.
This is how i've been trying to do it --
public void EditPanel(System.Web.UI.WebControls.Panel panel)
{
foreach (System.Web.UI.WebControls.TextBox t in panel.Controls)
{
t.Enabled = true;
}
}
Thanks!
You're looping over panel.Controls, which will loop over every control in the panel. This is not necessarily the same thing as looping over everything you've added. If there was something else inside the panel that existed when you started, you will end up getting that too.
What you probably wanted was this:
foreach (var t in panel.Controls.OfType<System.Web.UI.WebControls.TextBox>())
{
t.Enabled = true;
}
You are putting each textbox inside a "div" control which is HtmlGenericControl, then inside the panel control. So first you must search for the HtmlGenericControl inside panelId.Controls
A sample code that might help you:
public void EditPanel(System.Web.UI.WebControls.Panel panel)
{
foreach (Control c in panelId.Controls)
{
if (c is HtmlGenericControl)
{
foreach (var textbox in c.Controls.OfType<TextBox>()) //ofType returns IEnumerable<TextBox>
textbox.Enabled = true;
}
}
}
There is a control inside your Panel, that is not a TextBox and could not be cast to it. You should place a breakpoint before the loop and check the panel.Control collection contents in debug mode.
You can avoid the issue if you don't specify a type in the foreach loop and do the safe cast yourself.
foreach (var t in panel.Controls)
{
var textbox = t as System.Web.UI.WebControls.TextBox;
if(textbox != null)
{
textbox.Enabled = true;
}
}
You should check if control is TextBox
public void EditPanel(System.Web.UI.WebControls.Panel panel)
{
foreach (var t in panel.Controls)
{
if (t is System.Web.UI.WebControls.TextBox)
((System.Web.UI.WebControls.TextBox)t).Enabled = true;
}
}
The Controls collection will contain a collection of all the controls in the panel - not just TextBoxes. You can iterate through all of the controls and use the as operator to perform a type cast. If the type cast succeeds then you may enable the textbox.
public void EditPanel(System.Web.UI.WebControls.Panel panel)
{
foreach (var control t in panel.Controls)
{
System.Web.UI.WebControls.TextBox textBox = control as System.Web.UI.WebControls.TextBox;
if (textBox != null)
{
control.Enabled = true;
}
}
}
you add the textbox to the div element and the div element to the panel. therefore you need to select the controls in the panel and then find the textbox.
foreach (var t in panel.Controls.Cast<Control>().SelectMany(c => c.Controls))
{
if (t is TextBox == false) continue;
((TextBox)t).Enabled = true;
}

ASP.net -- Identifying a specific control in code behind

I have a page that holds 5 texboxes each name similar but with a numerial suffix. Example:
tbNumber1, tbNumber2, tbNumber3 and so on.
The reason it's like that is because those textboxes are generated dynamically based on some parameter. I never know how many textboxes will be need for a particular record.
How can I loop trough the text contents of these texboxes?
MY first instinct was to do something like the following, but that obviously does't work :)
for (int i = 0; i <= 3; i++)
{
string foo = tbNumber+i.Text;
//Do stuff
}
Wahts the best way to go trough each of these textboxes?
Thanks!!!
You might be able to do something like this:
for( int i = 0; i < upperLimit; i++ )
{
TextBox control = Page.FindControl("tbNumber" + i) as TextBox;
if( control != null ) {
// do what you need to do here
string foo = control.Text;
}
}
Possibly try something like
foreach(Control control in Page.Controls)
{
//Do stuff
}
If you're generating them dynamically, put them in a List<TextBox> as you generate them:
// in the Page_Load or whereever you generate the textboxes to begin
var boxes = new List<TextBox>();
for (int i = 0; i < numRecords /* number of boxes */; i++) {
var newBox = new TextBox();
// set properties here
boxes.Add(newBox);
this.Controls.Add(newBox);
}
Now you can loop through the textboxes without using crufty string techniques:
foreach (var box in boxes) {
string foo = box.Text;
// stuff
}
What you need is a recursive FindControl like function. Try something like this:
for (int i=0; i<3; i++)
{
Control ctl = FindControlRecursive(Page.Controls, "tbNumber", i.ToString());
if (ctl != null)
{
if (ctl is TextBox)
{
TextBoxControl tbc = (TextBox)ctl;
// Do Something with the control here
}
}
}
private static Control FindControlRecursive(Control Root, string PrefixId, string PostFix)
{
if (Root.ID.StartsWith(PrefixId) && Root.ID.EndsWith(PostFix))
return Root;
foreach (Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, PrefixId, PostFix);
if (FoundCtl != null)
return FoundCtl;
}
return null;
}
If you're using a CheckBoxList control you should be able to loop through each checkbox in the control.
foreach(var checkbox in checkboxlistcontrol)
{
string name = checkbox.Text;
}
If you're not using a CheckboxList control, you might want to consider using one as an option.

Categories