Working with a GridView in C# (ASP.NET) and I'm trying to iterate over a single row. Normally it wouldn't be too difficult if I could extract the text in each cell:
string text = SecGrpGridView.Rows[0].Cells[i].Text;
However, some of the fields in my row contain Labels and I believe the only way to extract the value is using FindControl() and casting it to a Label:
Label myLabel = (Label)SecGrpGridView.Rows[0].Cells[i].FindControl("Label5");
string text = myLabel.Text;
As you can see, the second example I needed to know the ID of my label so it makes it difficult to iterate over unless I have sequentially named labels. I know that a future need will be to add more columns to my row so I'm looking for a way to iterate over this row without having to name the labels sequentially. (ie 'Label1', 'Label2', 'Label3') Is there a better way to go about this?
You can gather all the Labels in GridView by using the following code
public static List<Label> FindLabelRecursive(Control root)
{
List<Label> labels = new List<Label>();
if (root is Label)
{
labels.Add(root as Label);
return labels;
}
foreach(Control c in root.Controls)
{
if (c is Label)
{
labels.Add(c);
}
else
{
List<Label> childLabels = FindLabelRecursive(c);
labels.AddRange(childLabels);
}
}
return labels;
}
Then do you processing based on the labels returned.
Related
I'm looking for an effective way of clearing textboxes, ideally in a function.
I have tried using:
{
Action<Control.ControlCollection> func = null;
func = (controls) =>
{
foreach (Control control in controls)
if (control is TextBox)
(control as TextBox).Clear();
else
func(control.Controls);
};
func(Controls);
}
The problem with the above solution is that I could not choose which text boxes were to be deleted.
TextBoxName.Text = "";
The above works however the only problem is that it takes up 200 lines
I have 61 boxes, i need a clear all button, that only clears 60 boxes (all except one)
i need clear row buttons, since the boxes are arranged in rows
there are 15 clear row buttons, each with 4 boxes, is there a for loop i can use that will only clear the ones i need (by name if possible)?
You could create a collection of TextBoxes to exempted and filter based on it. For example,
var exceptionList = new[] { textBox1 };
foreach(var textBox in Controls.OfType<TextBox>().Where(x=> !exceptionList.Contains(x)))
{
textBox.Clear();
}
If you want to filter based on the Control Name, you would use
foreach(var textBox in Controls.OfType<TextBox>().Where(x=> !exceptionList.Contains(x.Name)))
{
textBox.Clear();
}
Where exceptionList is collection of names of TextBoxes that needs to be exempted.
I have multiple textbox names such as R1TotalCost, R2TotalCost, R3TotalCost, all the way up to R25TotalCost. Is there anyway to edit the text values, and or text colours to them all using a code simular to this
for (i=1; i <=25, i++) {
string TextBoxName ="R" + i + "TotalCost";
TextBoxName.text = "£25";
TextBoxName.Foreground = Brushes.Green;
}
I think the best way to go about this since you seem to want to update them all at once, would be to create an Array or List that contains all of the TextBox elements. Then your can go through them all like below!
foreach (TextBox tb in myTextBoxes) {
tb.Content = "UPDATED CONTENT!";
}
I have a dynamically created asp table, which have 4 columns. First column is text, second textbox, third and fourth are text. I need to iterate through the table and get the value from textbox. But I am getting this exception when I am trying to get the textbox value : Specified argument was out of the range of valid values. I set the cell index as 1 as the textbox is located in second column. How can I get the text from textbox?
foreach (TableRow row in this.reading.Rows)
{
var textbox = (TextBox)row.Cells[1].Controls[1];
string id = row.Cells[3].Text;
if (textbox.Text != "")
{
double f = Convert.ToDouble(textbox.Text);
DBConn.update(f, id);
}
else
{
}
}
As dime2lo mentions its hard to find the error without debugging / providing more info.
Try instead of assigning textbox to the the 2nd control in the table row assign it to controls and remove your angle brackets.
var controls = row.Cells[1].Controls;
Then iterate through the controls
foreach (Control c Controls)
{
//Debug in here.
}
This will at least help you see where it's going wrong.
Great website - very helpful in my C# Class.
I am trying to write a method in C# that will Check fields for null entry and change field background to LightYellow?
The form is a display form that views records in a SQL database.
Here is what I tried - but the variable for the field names isn't translating to the field name.
Advice?
// YellowBack Method fills background of key fields that are missing data or are NULL
private void YellowBack()
{
//Bool fieldContents = true;
string fieldVariable;
string[] fieldName = { "activity_TitleTextBox", "act_Title2TextBox", "kid_NotesTextBox", "review_AdultTextBox",
"phoneTextBox", "addressTextBox", "cityTextBox", "websiteTextBox", "weblink_TextTextBox",
"hoursTextBox", "admissionTextBox" };
int count = 0;
//Check each field name
for (int index = 0; index < fieldName.Length; index++)
{
fieldVariable == fieldName.Text;
if (fieldVariable.Trim = "")
{
fieldVariable.BackColor = LightYellow;
}
else
{
fieldVariable.BackColor = Window;
}
}
}
You are not using the index . . . . you should be using something like:
fieldVariable = fieldName[i].Text;
I also think that you won't be able to set the property BackColor on fieldVariable as it is a string. You should probably be using the object grid or text control that your database binds to and setting the color properties of that . . . but I'm not sure there's enough information here to go on.
I think the problem is that you're looping through a list of strings and trying to make the string into a TextBox control. Instead, you should probably loop through all the controls on the form, and for each one that is a TextBox, see if it's name matches a name in your list. Then you can set the back color of the control based on the Text property.
There are other problems with your code also, like in your if statement you are doing an assignment (=) instead of a comparison (==).
Here's what I would do:
private void HighlightEmptyFields()
{
// Create a list of all the text box names that we want to examine
var textBoxNames = new List<string>
{
"activity_TitleTextBox", "act_Title2TextBox", "kid_NotesTextBox",
"review_AdultTextBox", "phoneTextBox", "addressTextBox", "cityTextBox",
"websiteTextBox", "weblink_TextTextBox", "hoursTextBox", "admissionTextBox"
};
// Loop through every control on the form
foreach (Control formControl in this.Controls)
{
// Find the groupbox control by name
if (formControl.Name != "groupBox1") continue;
// We found the group box, so loop through every control in it
foreach (Control groupBoxControl in formControl.Controls)
{
// Try to cast the control to a TextBox.
var textBoxControl = groupBoxControl as TextBox;
// If the cast fails, move on to the next one...
if (textBoxControl == null) continue;
// Now we have one a textbox control, so see if the
// textBoxNames array contains the name of this text box.
if (textBoxNames.Contains(textBoxControl.Name,
StringComparer.OrdinalIgnoreCase))
{
// We found a match, so set the backcolor based on Text property
if (textBoxControl.Text.Trim() == "")
{
textBoxControl.BackColor = Color.LightYellow;
}
else
{
textBoxControl.BackColor = Color.White;
}
}
}
// Since we found the control we were looking for, we can stop looking
break;
}
}
In my form i have a "plus-button", when the user click on it a new TextBox is added to the form:
private void btnPlus_Click(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.Name = "textBox" + countTb.ToString();
this.Controls.Add(tb);
countTb++;
}
My problem is: I don't know how to access these TextBoxes.
I have a save-button, when user clicks it i have to save all TextBox.Text into database, but I don't know how to find them.
You could use Controls.OfType if the TextBoxes are on top of the form:
var allTextBoxes = this.Controls.OfType<TextBox>();
foreach(TextBox txt in allTextBoxes)
{
// ...
}
Another approach is to use ControlCollection.Find to find controls with a given name:
for(int i = 1; i <= countTb; i++)
{
Control[] txtArray = this.Controls.Find("textBox" + i, true); // recursive search
if (txtArray.Length > 0)
{
TextBox txt = (TextBox)txtArray[0];
}
}
you can easily save button names on array or you can access to form text boxes from --> this.controls
To get all of the TextBoxes on the form, you can do the following:
var textBoxes = this.Controls.OfType<TextBox>();
Then you can iterate over them all to get their text values:
foreach(var textBox in textBoxes)
{
var text = textBox.Text;
//do something to save the values.
}
One of the best ways to access the text box after you have created it would be to insert it into an array or list, this way you would be able to iterate through that list/array to access any number of text boxes and save the data inside to a database.
If you want to save all TextBox.Text values on the form in one comma-delimited string:
var allText = string.Join(",", Controls.OfType<TextBox>().Select(x => x.Text));
You'll need to clarify your question more, if this won't work.
This will grab the value of every TextBox on the form, so if you don't want to save the values from some, you'll need to filter them out first.
If you want a list, so you can save one record per TextBox, then remove string.Join.