C# multiple checkboxes - c#

I have 10 checkboxes on my form. They are named checkBox1, checkBox2, ..., checkBox10.
At the moment my code looks like this:
if(checkBox1.Checked)
Call MyFunction(1);
if(checkBox2.Checked)
Call MyFunction(2);
etc
Because the argument I pass to my function is the same as the checkbox number, I would like to use a for loop, so that for each checkbox_i, I should call MyFunction(i)
Thanks,
Nick

Not very safe, but simple way:
int index = 1;
foreach (var checkBox in this.Controls.OfType<CheckBox>())
{
if (checkBox.Checked)
{
MyFunction(index);
}
index++;
}
Next idea is safer, but not very elegant:
foreach (var checkBox in this.Controls.OfType<CheckBox>())
{
if (checkBox.Checked)
{
int index = int.Parse(checkBox.Name.Substring(8));
MyFunction(index);
}
}
Ultimately, best is to populate .Tag property of all checkboxes with appropriate indices. In this solution you could even skip some checkboxes like this:
foreach (var checkBox in this.Controls.OfType<CheckBox>().Where(c => c.Checked))
{
int? index = checkBox.Tag as int;
if (index.HasValue)
{
MyFunction(index.Value);
}
}
And even more readable way would be to have a list of checkboxes you are interested in this process in your form's constructor for example:
relevantCheckBoxes = new List<CheckBox>();
relevantCheckBoxes.Add(this.checkBox1);
relevantCheckBoxes.Add(this.checkBox3);
// etc.
And then:
for (int index = 0;index < relevantCheckboxes.Count;++index)
{
if (relevantCheckboxes[index].Checked)
{
MyFunction(index);
}
}

ok there are property in any control name Name check this pesodo code
Checkbox t=CheckBox(object);
var number=t.name.substring("checkbox".length,name.length-"checkbox".length) // to get only number or you can split name by regular expression
myfunction(int.parse(number));
// try this code and and ask here agine if any problem due to I can't test it now

Related

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

property return text from each row datagridview

I need a property that returns text for each row from my datagridview. I don't know if the way how I am doing may work .It says on get that i is not in the current context . My code:
TextBox[] text1=new TextBox[100];
public string [] RowText
{
get
{
return text1[i].Text;
}
set
{
int i = 0;
foreach (DataGridViewRow row in datagridview1.Rows)
{
for ( i = 0; i < datagridview1.Rows.Count; i++)
{
text1[i].Text= row.Cells[i].Value.ToString();
}
}
}
}
First of all if i is not a global variable then it should be declared inside get clause. Then text1[i].Text return single string but your Property returns an array, so change it to:
get
{
return new string[] { text1[i].Text };
}
also your set does not make much sense. If you explain better what you want to achieve maybe I may help you out.
First of all, you don't need the setter - put the code in the getter or in the object's constructor. And you are returning an array of TextBox objects but your property signature states you are returning an array of strings.
If you want to return a string array, then perhaps:
public string [] RowText
{
get
{
List<string> text = new List<string>();
foreach (DataGridViewRow row in datagridview1.Rows)
{
text.Add(row.Cells[i].Value.ToString());
}
return text.ToArray();
}
}
Actually, looking closer at your code, it may fail because of the for loop. Your code assumes that the row contains the same number of cells as there are rows. This may be true for your scenario, but unlikely.

replacing an object in listview with new one?

I have a listview with few items. I am using foreach loop to check if there is a match. The code I am using looks like this:
foreach (ListViewItem test in listView1.Items)
{
if (test.SubItems[1].ToString() == item.SubItems[1].ToString())
{
test.Tag = item.Tag;
}
}
What I am trying to do is, check the 2nd index and if there is a match replace the old item 'test' with the new one 'item'.
Apparently there is no change in the listview. Is the way I am replacing the object wrong?
you can clone the item and assign directly to the list view item. but you need to change foreach loop to for loop.
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].SubItems[1].ToString() == item.SubItems[1].ToString())
{
listView1.Items[i] = (ListViewItem)item.Clone();
}
}
You have updated the Tag only. You need to change test.SubItems[0], test.SubItems[1],... to see the changes.
Or you could remove old item and insert new item by using listView1.Items.Remove(...) or listView1.Items.RemoveAt(...) and listView1.Items.Insert(...). But if you need to pay account of performance you should use the first algorithm (changing test.SubItems[i]).

CheckedListBox - Search for an item by text

I have a CheckedListBox bound to a DataTable. Now I need to check some items programmatically, but I find that the SetItemChecked(...) method only accepts the item index.
Is there a practical way to get an item by text/label, without knowing the item index?
(NOTE: I've got limited experience with WinForms...)
You can implement your own SetItemChecked(string item);
private void SetItemChecked(string item)
{
int index = GetItemIndex(item);
if (index < 0) return;
myCheckedListBox.SetItemChecked(index, true);
}
private int GetItemIndex(string item)
{
int index = 0;
foreach (object o in myCheckedListBox.Items)
{
if (item == o.ToString())
{
return index;
}
index++;
}
return -1;
}
The checkListBox uses object.ToString() to show items in the list. You you can implement a method that search across all objects.ToString() to get an item index. Once you have the item index, you can call SetItemChecked(int, bool);
Hope it helps.
You may try to browse your Datatable. YOu can do a foreach on the DataTabke.Rows property or use SQL syntax as below:
DataTable dtTable = ...
DataRow[] drMatchingItems = dtTable.Select("label = 'plop' OR label like '%ploup%'"); // I assumed there is a "label" column in your table
int itemPos = drMatchingItems[0][id]; // take first item, TODO: do some checking of the length/matching rows
Cheers,
I am answering it very late, I hope it will help someone. If you want to find any item by name we can do it in two steps. First get index of item by text and then we can get actual item with the help of index.
var selectedItemIndex = cbxList.Items.IndexOf("sometext");
var selectedItem = cbxList.Items[selectedItemIndex];

Select the specific column of ListView and print it in a new messagebox in C#.net

I've just started to use ListView in C#.net.
I got to know how to add items and subitems. Going through the listview I wanted to fetch all the data from a whole column with multiple rows.
I want to know how to do this.
I found this code to list a specific selected data from a row:
ListView.SelectedIndexCollection sel = listView1.SelectedIndices;
if (sel.Count == 1)
{
ListViewItem selItem = listView1.Items[sel[0]];
MessageBox.Show(selItem.SubItems[2].Text);
}
That was helpful but i want to list all the items in a row, may be i want to add all the column items in array?
private string[] GetListViewItemColumns(ListViewItem item) {
var columns = new string[item.SubItems.Count];
for (int column = 0; column < columns.Length; column++) {
columns[column] = item.SubItems[column].Text;
}
return columns;
}
I would recommend some caution against doing this. A ListView is really meant to display information, it is not a great collection class. Getting the data out of it is slow and crummy, it can only store strings. Keep the data in your program in its original form, maybe a List<Foo>. Now it is simple and fast.
foreach (ListViewItem item in listView1.Items) {
// Do something with item
}
you could do this by
foreach(ListViewItem item in listView1.Items)
{
foreach(var subtem in item.SubItems)
{
// Do what ever you want to do with the items.
}
}

Categories

Resources