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;
}
}
Related
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.
I've got a for loop to read line by line of a stream reader. This works very well. Now I've problems with reading the file of the stream reader. It's a csv file that contains two columns with information. The first one (A) contains a C# element like a textbox or a label (just like "label_1_title"), which is declared in my project. The second one (B) contains a normal simple string like "Hello".
Now I want to convert the string content of column A to the real existing element. Example: I've got "label_1_title" written in column A and that's an element, that exists in my project. Now I want to use this element to (for example) change it's content to the content of the column B of that line.
public void SetSprachpaket(string Sprachpaket)
{
StreamReader StreamReader = new StreamReader(Sprachpaket, Encoding.UTF8);
string Inhalt = StreamReader.ReadLine();
for (int i = 1; Inhalt != null; i++)
{
var Items = Inhalt.Split(new Char[] { ';' });
object Element = Items[0].GetType(); // Convert the string content of Items[1] to the existing object
Element = Items[1]; // Take this existing object and give it the string content of Items[2]
Inhalt = StreamReader.ReadLine();
}
StreamReader.Close();
}
I hope you can help me. Thanks in advance. Kind regards.
EDIT:
object Element = Items[0].GetType(); // Get (let's say) the string "myString"
Element = Items[1]; // --> myString = ...
Please don't rely on internal naming within your project. You should have some kind of explicit mapping between elements and the column data.
Dump the CSV file into a Dictionary<string, string> of Column A => Column B. On the element containing all the elements you want to populate, set the DataContext to the dictionary. Define your labels like this:
<Label Content="{Binding [label_1_title]}" />
For more details, see Data Binding Overview. This will look up the dictionary key "label_1_title" and set the content to the value when the label loads.
In case you want to use additional data binding other than the label dictionary, I recommend you use a custom object for the DataContext, that stores the dictionary in a property such as LabelDictionary. In this case the binding should be:
<Label Content="{Binding LabelDictionary[label_1_title]}" />
Simply by using foreach
foreach(control x in this.Control)
{
if(x.Name == A) // For A means the name of the object
{ x.Text = B; } // For B means the string
}
This is not ideal, you'll need to play around with it, but somewhere in the direction you are looking for I think.
while (Inhalt != null)
{
switch (Items[0])
{
case "label"
element = new Label();
element.Text = Items[1];
break;
case "textbox"
element = new Textbox();
element.Text = Items[1];
break;
case "numericUpDown"
element = new NumericUpDown();
element.Value = Item[1];
break;
}
}
Edit : if you are not wanting to populate the form from scratch, use this.Controls.Find() to find the control with that name.
If the items[0] is the name of the control you can do this to find the Control
this.Controls.Find(items[0])
you might then have to cast it to the appropriate type depending on which property you wish to assign to
control.Text = items[1];
Assuming that the first column is the name of a field in the same class and not the name of a control you could do this
var field = this.GetType().GetField(items[0],
BindingFlags.Instance
| BindingFlags.NonPublic);
var control = (Control)field.GetValue(this,null);
control.Text = items[1];
(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
}
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
}
I have quite a few radiobuttonLists in my ASP.net webform. I am dynamically binding them using the method shown below:
public static void PopulateRadioButtonList(DataTable currentDt, RadioButtonList currentRadioButtonList, string strTxtField, string txtValueField,
string txtDisplay)
{
currentRadioButtonList.Items.Clear();
ListItem item = new ListItem();
currentRadioButtonList.Items.Add(item);
if (currentDt.Rows.Count > 0)
{
currentRadioButtonList.DataSource = currentDt;
currentRadioButtonList.DataTextField = strTxtField;
currentRadioButtonList.DataValueField = txtValueField;
currentRadioButtonList.DataBind();
}
else
{
currentRadioButtonList.Items.Clear();
}
}
Now, I want to Display only the first Letter of the DataTextField for the RadioButton Item Text.
For example if the Value is Good I just want to Display G. If it Fair I want to display F.
How do I do this in C#
Thanks
You can't do what you want when you do the binding, so you have 2 options:
Modify the data you get from the table, before you do the binding.
After binding, go through each item and modify its Text field.
So, it you want to display "only the first Letter of the DataTextField for the RadioButton Item Text", you can do:
currentRadioButtonList.DataSource = currentDt;
currentRadioButtonList.DataTextField = strTxtField;
currentRadioButtonList.DataValueField = txtValueField;
currentRadioButtonList.DataBind();
foreach (ListItem item in currentRadioButtonList.Items)
item.Text = item.Text.Substring(0, 1);
If I misunderstood you and you want to display the first letter of the Value field, you can replace the last two lines with:
foreach (ListItem item in currentRadioButtonList.Items)
item.Text = item.Value.Substring(0, 1);
You could add a property to the type that is being bound (the one that contains Good, Fair, etc.) and bind to this property. If you will always be using the first letter, you could make it like so (adding in null checks, of course):
public string MyVar { get; set; }
public string MyVarFirstChar
{
get { return MyVar.Substring(0, 2); }
}