I am validating data in a textbox if nothing is entered
public bool IsPresent(TextBox textBox, string name)
{
if (textBox.Text == "")
{
MessageBox.Show(name + " is a required field.", "Entry Error");
textBox.Focus();
return false;
}
return true;
}
However, I want to pass in the name argument as the actual name from the dataset datacolumn that the textbox is bound to.
public bool isValidData(List<TextBox> textBoxList)
{
foreach (TextBox textBox in textBoxList)
{
//string name = techSupportDataSet.Technicians.NameColumn.ColumnName;
IsPresent(textBox, name);
}
return false;
}
You can see that the commented out code explicitly gets a specific datacolumn name, but I want it to be a variable depending on the bound textbox.
I've tried looking up the MSDN docs but I can't seem to find any methods that would accept a bound control as a parameter. Any points in the right direction would be much appreciated!
Displaying a field name in message box is not a good idea. for example if DBA has created a field FName for User's First Name then the message will be displayed like FName is a required field. This will confuse the operator. You can assign the Display Name in that control's AccessibleName or AccessibleDescription property and then you can use it in your code.
//Assign display name in AccessibleName property
textBox.AccessibleName= "User's First Name"
//use that field
IsPresent(textBox, textBox.AccessibleName);
Related
I have a long list of check boxes that I need to display on a form. I get the list of check boxes from a table in the database and render them on the page. When the page is saved, I am saving the field name and value (as they are stored in the database) of each selected item.
I also have a model class that all of these check box fields map to, but I was thinking, since I have the field name and value, I would be able to set only the properties for which I have a field/value.
I was thinking I could just do something like this, but I know the syntax isn't correct:
private void CreatePPAIndication(ReferralFormViewModel viewModel, Guid personId, Guid encId)
{
var ppaIndication = new PPAIndication();
ppaIndication.enterprise_id = "00001";
ppaIndication.practice_id = "0001";
ppaIndication.person_id = personId;
ppaIndication.enc_id = encId;
// set more properties...
// Here is where I would set a property for each selected check box.
foreach (var indication in viewModel.Indications.Where(o => o.IsSelected))
{
var result = "ppaIndication." + indication.FieldName + "(" + indication.FieldValue + ")";
}
// How can I essentially "execute" the string in the line above?
_context.PPAIndications.Add(ppaIndication);
}
So, basically, I am wondering how I can essentially "execute" the "result" string as real code. Thank you in advance for any advice!
you can use reflection for that
something like
GetType().GetProperty(o.FieldName).GetValue(indication, null);
to get the value
or
GetType().GetProperty(o.FieldName).SetValue(indication, o.Value);
to set the value
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;
}
}
I'm new with Sharepoint 2013 AND .NET c# so take it easy guys.
I'm writing a webpart which generates input forms dynamically. Each form may have different fields so field names/IDs are defined on runtime.
This is the code I generate a input text. fieldname is my variable here which is the ID and preferably the name of the input box. fieldtitle is the display name and fielddefaultvalue is the default value. This code part is in a loop and adds all inputs into PlaceHolder1 every time.
TextBox formfield = new TextBox();
formfield.ID = fieldname;
formfield.Text = fielddefaultvalue;
formfield.Attributes.Add("placeholder", fieldtitle);
PlaceHolder1.Controls.Add(formfield);
What my problem is, when I run this, name and ID of my input fields become like
ctl00$ctl39$g_76a6fb01_d2b4_4087_a988_8b34b95dc136$Email
I tried to get submitted values using
Page.Request.Form["Email"]
but no success. I guess it needs all those random characters too.
I could also use Email.Text to get value but Email part is dynamic and comes from a variable. Is there a way to use variable fieldname which contains Email and other field names as string?
How can I get submitted values and/or put clean names to my input fields.
Remember my field names are dynamic and kept in fieldname variable every round of the for loop.
Edit
After I submit form, this is the debug screen of Page.Request.Form . I don't know how/where I can find that random/unique string at the beginning of each input field. flexiforms_xxx part is the actual filed name.
You could cache the TextBoxes in a dictionary when adding them:
Dictionary<string, TextBox> textBoxesByFieldName = new Dictionary<string, TextBox>();
foreach(string fieldName in FieldNames){
TextBox formfield = new TextBox();
formfield.ID = fieldname;
formfield.Text = fielddefaultvalue;
formfield.Attributes.Add("placeholder", fieldtitle);
PlaceHolder1.Controls.Add(formfield);
textBoxesByFieldName.Add(fieldname, formfield);
}
And when you need them access the TextBox this way:
private TextBox GetTextBoxByFieldName(string fieldName){
TextBox textBox;
return textBoxesByFieldName.TryGetValue(fieldName, out textBox) ? textBox : null;
}
[edit] If I understand correctly you want to submit the form and get all the entered text for your clean field names:
void OnSubmitButtonClick(Object sender, EventArgs e)
{
foreach(KeyValuePair<string, TextBox> keyValue in textBoxesByFieldName){
string fieldName = keyValue.Key;
string fieldValue = keyValue.Value.Text;
}
}
[edit2] Above solution requires formfield.AutoPostBack=true; to be set
To avoid page refreshes, use string fieldValue = Page.Request.Form[((System.Web.UI.Control)(keyValue.Value)).UniqueID];
Have you tried: formfield.ClientId
Request.Form[...] requires the name or index of the control, so set the Name of the control
formfield.Name = fieldname;
http://msdn.microsoft.com/en-us/library/ms525985(v=vs.90).aspx
I have this in Load of my form which contains combobox (cmbTip)
EventTypeRepository tip = new EventTypeRepository();
cmbTip.DataSource = new BindingSource(tip.FindAll(), null);
cmbTip.DisplayMember = "Value";
cmbTip.ValueMember = "Key";
(FindAll() is a method in EventTypeRepository which returns Dictionary(string, EventType>))
For some reason this displays MyProject.Model.EventType as all combobox items. I even added:
public string toString()
{
return _name + "(" + _id + ")";
}
in my EventType class, but it stills displays names as MyProject.Model.EventType (there are as many items as there are event types, so I think it works fine expect for displaying names). I have no idea how to fix this...
You should override ToString method (keep in mind C# is case-sensitive language):
public override string ToString()
{
return String.Format("{0}({1})", _name, _id);
}
Also it's better to set DisplayMember and ValueMember before you set DataSource.
If you ever find your self in a situation where you can't override ToString(), another option is to use the Format event built in to the combo box. First you must set FormattingEnabled to true on the combo box, then subscribe to the Format event and use code similar to the following.
private void cmbTip_Format(Object sender, ListControlConvertEventArgs e)
{
var item = (EventType) e.ListItem;
e.Value = String.Format("{0}({1})", Name, Id);
}
This assumes that _name and _id have corresponding public properties Name and Id.
(Asp.net/C# VS2008)
I have a datagrid populated by a database and when pressing Edit, a form opens and populates fields/controls from that datagrid line.My issue lies when trying to populate a dropdownlist box, which has a datasource from an ENum List.I Just cannot get the text from the datagrid cell to show up in the ddL, it should also equal one of the Enum Items and auto select it.
My Code
Pull from the datagrid cell gives me “Low”
ddl_reg.Text = e.Item.Cells[25].Text;
public void Populate_regstatus_dropdownlist()
{
//if (!IsPostBack)
//{
// ddl_reg.DataSource = Enum.GetNames(typeof(regstatus));
// ddl_reg.DataBind();
//}
//if (!IsPostBack)
//{
// foreach (int value in Enum.GetValues(typeof(regstatus)))
// {
// ddl_reg.Items.Add(new ListItem(Enum.GetName(typeof(regstatus), value), value.ToString()));
// }
//}
ddl_reg.DataSource = Enum.GetNames(typeof(regstatus ));
//ddl_reg.DataValueField = regstatus;
//ddl_reg.DataTextField = "Low";
//ddl_reg .SelectedItem = Enum.GetName(typeof (regstatus ));
ddl_reg.DataBind();
//ddl_reg.SelectedIndex = ddl_reg.Items.IndexOf(ddl_reg.Items.FindByText("Low"));
}
public enum regstatus
{
NotSelected,
Low,
Medium,
High
}
Error received is;
ddl_reg' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
I am new to C# but through searching your site i realise this means the value is not seen or has not been pulled and would really apreciate some help, or pointing in the right direction, cheers.
I believe the problem is that the drop down list doesn't contain the item you are passing. You may check it before changing the selected value. Other chances are that the value you are getting from e.Item.Cells[25].Text may contain spaces, so you may trim before setting it to the drop down.
if (ddl_reg.Items.FindByText("Low") != null)
{
ddl_reg.Text = e.Item.Cells[25].Text;
}
else
{
//Not found
}