I'm trying to update a person's details in the database. Since I'm using textboxes, how would I keep the original value if the textbox is empty?
I'm trying to write it in a short way rather than having a tonne of IF statements.
The code I've written will work but not the way I want, any suggestions on what I could do?
Code (C#):
foreach (Control c in pnlUpdate.Controls)
{
if (c is TextBox)
{
TextBox questionTextBox = c as TextBox;
if (questionTextBox.Text == "")
{
questionTextBox.Text = pat[0].Forename;
questionTextBox.Text = pat[0].Surname;
questionTextBox.Text = pat[0].Street;
questionTextBox.Text = pat[0].Town;
questionTextBox.Text = pat[0].City;
questionTextBox.Text = pat[0].DOB.ToString();
questionTextBox.Text = pat[0].House_number;
questionTextBox.Text = pat[0].Mobile;
}
}
}
Pat = database object
I'm trying to update a person's details in the database. Since I'm using textboxes, how would I keep the original value if the textbox is empty?
Use Server Validation. To make sure that user has entered values for all controls you need to use RequiredFieldValidator. Go through below link:
http://msdn.microsoft.com/en-us/library/5hbw267h(v=vs.80).aspx
Something like below will provide you the help
pat[0].Name = TextBox.Text == "" ? pat[0].Name : TextBox.Text
Related
I want to capture all the textboxes values on button click in string without explicitly writing each of this line for each textbox in c# like
string atv1 = TextBox1.Text;
string atv2 = TextBox2.Text;
It should find all textboxes and make a string of it (join) .
can anyone help out !!
(window form when making some asp.net website (c#))
concise way :
String.Join(",",Form.Controls.OfType<TextBox>().Select(c => c.Text))
You can use a StringBuilder to "join" (most software types use the term concatenate) the strings. To get all the TextBoxes you can select any control on the form that is a text box. Simple solution is
var s = new StringBuilder();
foreach (var textbox in this.Controls.OfType<TextBox>())
{
s.AppendLine(textbox.Text)
}
Console.WriteLine(s.ToString());
However, a TextBox can be inside of a Control on the Form. So to handle this case you need recursion. I'll leave you to search StackOverflow to figure out how to do this.
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
var txt = (TextBox)c;
//Do Something
}
}
More elegant way:
var objTextboxValues = this.Controls.OfType<TextBox>().Select(obj => obj.Text).ToList();
var varJoinedText = String.Join(", ", objTextboxValues);
Original Answer:
var varAllTextBoxValues = "";
foreach (Control objControl in this.Controls)
if (objControl is TextBox)
varAllTextBoxValues += ((TextBox)objControl).Text;
}
MessageBox.Show(varAllTextBoxValues);
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.
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.
Basically I have 3 arrays of different types:
control = new Control[2] { txtRecordDelimeter, txtFieldDelimeter };
name = new string[2] { "Record Delimiter", "Field Delimiter" };
exists = new bool[2] { false, false };
...essentially I would like to create a loop that checks whether the string existed in an object passed into a constructor, if did, set the bool of the respective index to true and then ammend the respective control with a new value.
Originally I had a bunch of if statements and repeating code so I wanna cut that out with a for loop.
However, for example, when I attempt to reference control[0].whatever I get the same list from IntelliSense regardless of whether or not the control is a text box or a combo box etc.
I'm guessing I'm missing something simple here like not referencing an instance of the control per se, but I'd be greatful if someone could explain what I'm doing wrong or suggest a better way to achieve this!
Thanks :]
Your Control[] array contains Control objects, not TextBox'es etc. You have to cast each particular object in order to use other properties. You can try this:
if(Control[i] is TextBox) (Control[i] as TextBox).Text = "Yeah, it's text box!";
if(Control[i] is CheckBox) (Control[i] as CheckBox).Checked = true;
I think you mean something like this:
for(int i = 0; i < control.Length; i++)
{
TextBox textBox = control[i] as TextBox;
if(textBox != null)
{
if(textBox.Text == name[i])
{
exists[i] = true;
continue;
}
}
}
you are getting same list from intellisense because all the elements in array are of Control type. You will need to Explicitely cast the Control to (TextBox) or (ComboBox).
lie this:
foreach(Control ctrl in control)
{
TextoBox tbx = ctrl as TextBox;
if(tbx != null)
{
//do processing
continue;
}
ComboBox cbx = ctrl as ComboBox;
if(cbx != null)
{
//do processing
continue;
}
//and so on
}