Access controls that were created at run time - c#

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.

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.

C# Updating multiple text boxes with similar names

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

Check fields for null entry and change field background to lightyellow?

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

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