C# Updating multiple text boxes with similar names - c#

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!";
}

Related

Is there a more line efficient way of clearing textboxes in C#?

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.

Access controls that were created at run time

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.

Iterate through GridView Row with Labels

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.

set combobox text from textbox

I have user submitted content that is loaded into c# winform in our office for processing before officially added to database. The user can submit a 'Referrer' as two text fields-first and last name. In the office I want to have a combobox will all existing referrers loaded in, then the first couple letters of the name to advance the combobox down to the area it needs to be at. I want to do something like this, taking the first two letters of the name and use that to initialize the combobox.
if (txtrefFirstName.TextLength > 2)
{
string firstStart = "" + txtrefFirstName.Text[0] + txtrefFirstName.Text[1];
firstStart = firstStart.ToUpper();
ddlReferring.SelectedText.StartsWith(firstStart);
}
else
ddlReferring.Text = "";
Any ideas or suggestions to get this to work?
Thanks
David K.
You could write something like this...
foreach (string item in ddlReferring.Items)
{
if (item.StartsWith(firstStart))
{
ddlReferring.SelectedText = item;
break;
}
}
Assuming the ddl's datasource is a List of String objects, you should be able to do some comparison on the datasource itself. I tend to use Linq for things like this but it isn't strictly necessary, just shorter.
if (txtrefFirstName.TextLength > 2)
{
string firstStart = txtrefFirstName.Text.Substring(0,2).ToUpper();
string Selection = ddlReferring.DataSource.Where(a=>a.StartsWith(firstStart)).FirstOrDefault();
ddlReferring.SelectedText = Selection ?? "";
}
else
ddlReferring.Text = "";
The selection line can also come from the items collection directly
string Selection = ddlReferring.Items.OfType<string>().Where(a=>a.StartsWith(firstStart)).FirstOrDefault();
Or if you REALLY dont want to use Linq...
string Selection = "";
foreach (object item in ddlReferring.Items)
if (item.ToString().StartsWith(firstStart))
{
Selection = item.ToString();
break;
}
Similar methods can be used even if the ddl's data is not a list of strings, just make sure to cast the items appropriately and compare the correct values.

Populate textbox from checkbox list using ASP.NET and AJAX

I have a textbox control and a checkbox list control on my page.
I am first populating my checkbox list with a list of employee objects in the code-behind. An employee has an id and a name. Both are displayed in the checkbox list like so:
Jim (1)
Alex (2)
Gary (3)
When a user checks one of the boxes, the employee's name needs to be populated in the textbox. So if Jim is selected, the textbox value is "Jim". It also needs to support multiple values, so if Jim and Gary are selected, the textbox value is "Jim, Gary".
Also, if a user enters a valid value in the textbox, the correct employee should be checked. This needs to support names and id's. So if I enter "1,Alex" in the textbox and then click outside the textbox, Jim and Alex should be selected.
I'm using ASP.NET and I need to do this using AJAX, but I have no experience with using jQuery and AJAX. Could someone show me a simple example of how to do this?
Here is something I through together that might help get you started. It's not tested and not complete but I don't have time to do it all right now, so thought this might help. There definitely needs to be a lot more checks and paring done that I left out for you to implement.
$(function() {
// gets all checkbox items by a common class you will put on all of them
$('.checkboxlistclass').click(function(e) {
var txt = $(this).text();
var employeeName = txt; // change this to parse out the name part and remove the id
var currentTxtVal = $('#textboxid').val();
var newVal = currentTxtVal + ',' + employeeName; // check if you need the comma or not
$('#textboxid').val(newVal);
});
// textboxid is the id of the textbox
$('#textboxid').change(function(e) {
var textboxVal = $(this).val();
// split on the comma and get an array of items
// this is dummy data
var items = [];
items.push('Jim');
items.push(2);
// go through all the items and check if it's a number or not
// if it's a number do a selection based on the id in parenthesis
// if not then check first part for name match
for (var i=0; i < items.length; i++) {
if (isNaN(parseInt(items[i])) {
$(".checkboxlistclass:contains('" + items[i] + " ('").attr('checked', true);
}
else {
$(".checkboxlistclass:contains(' (" + items[i] + ")'").attr('checked', true);
}
}
});
});

Categories

Resources