I know how to set item to checked:
checkedListBox.SetItemChecked(index, true);
but i am having it called when i am opening form with parameter of int[] valueMembers so i want to check every value member that is = to this parameter to checked. Here is what i have tried:
public NovaPoruka(int[] primalacID)
{
InitializeComponent();
foreach(CheckedListBox o in checkedListBox1.Items)
{
if(primalacID.Contains(Convert.ToInt32(o.SelectedValue)))
{
o.SetItemChecked(o.SelectedIndex, true);
}
}
}
Edit:
I haven't seen that i didn't initialize checkedListBox before doing this so it wasn't dropping error but now when i made that i drops me error at CheckedListBox o in checkedListBox1.Items so i made little change but still do not know how to get index of current item that is inside foreach loop. Here is changed code:
foreach(Int_String o in checkedListBox1.Items)
{
if(primalacID.Contains(Convert.ToInt32(o._int)))
{
checkedListBox1.SetItemChecked(checkedListBox1.SelectedIndex, true);
}
}
current way of getting selected index returns me -1
I have done it. Here is final code:
for(int i = 0; i < checkedListBox1.Items.Count; i++)
{
Int_String s = checkedListBox1.Items[i] as Int_String;
if(primalacID.Contains(s._int))
{
checkedListBox1.SetItemChecked(i, true);
}
}
Related
I have a data grid and it is empty at first. Then I need to add items when the user selects some data. But here it shows error like
Error :
System.InvalidOperationException: Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.
I really didn't understand what is the problem here.
I have tried datagridName.Items.clear(); and datagridName.Items.Add();. but both did't work.
private void TextboxBarCodeTextchanged(object sender,RoutedEventArgs e)
{
DataGridSalesDetails.Items.Clear();
for (int i = 0; i < AllStockList.Count; i++)
{
if (!string.IsNullOrEmpty((sender as TextBox).Text))
{
if (AllStockList[i].BarCode.StartsWith((sender as TextBox).Text,
StringComparison.InvariantCultureIgnoreCase))
{
Stock vend = AllStockList[i] as Stock;
DataGridSalesDetails.Items.Add(vend);
DataGridSalesDetails.Visibility = Visibility.Visible;
DataGridSalesDetails.Items.Refresh();
TotalReturnAmount = AllStockList.Sum(a => a.TotalAmount);
HiddenTotalAount.Text = TotalReturnAmount.ToString();
LabelFinalAmountValue.Content = TotalReturnAmount.ToString();
}
}
}
}
Expected Result is the Datagrid with added values. What I get is an error. Is there anyone to help me? I'm stuck with my project.
When working with datagrids you should assign a collection of items to the itemSource of that datagrid. Instead of assigning the collection to the itemSource, you are trying to add a new item to that datagrid.
You'll need to filter the Stock objects you are interested in and add these to a collection.
When the iteration is completed and the Stock objects are added to the collection, you'll need to assign the collection to the ItemSource.
Update from OP
The itemssource of the datagrid is bound to an Observable collection.
And OP wants to save the old list of Stock Object Items.
ObservableCollection<Stock> StockItems = new ObserveableCollection<Stock>();
private void TextboxBarCodeTextchanged(object sender,RoutedEventArgs e)
{
oldCollection = ObservableCollection;
for (int i = 0; i < AllStockList.Count; i++)
{
if (!string.IsNullOrEmpty((sender as TextBox).Text))
{
if (AllStockList[i].BarCode.StartsWith((sender as TextBox).Text,
StringComparison.InvariantCultureIgnoreCase))
{
var stock = AllStockList[i] as Stock;
StockItems.Add(stock);
}
}
}
DataGridSalesDetails.Visibility = Visibility.Visible;
TotalReturnAmount = filteredCollection.Sum(a => a.TotalAmount);
HiddenTotalAount.Text = TotalReturnAmount.ToString();
LabelFinalAmountValue.Content = TotalReturnAmount.ToString();
}
I'm making a program that has to count how many CheckBox controls are checked, only in a GroupBox.
I've tried a lot of different ways but I can't get it work.
How can this be made?
// This is one of the many things I tried...
public CheckBox rNum;
//This method is used on FormLoad.
public void CreateBoxes()
{
for (int i = 0; i < 36; i++)
{
rNum = new CheckBox();
rNum.Text = i.ToString();
//CheckBoxes added to flowLayoutPanel.
flw.Controls.Add(rNum);
}
}
public int count;
//This method is used on Button Click
public void CountIt()
{
foreach (CheckBox box in groupBox.Controls.OfType<CheckBox>())
{
if (box.Checked)
{
count++;
}
}
MessageBox.Show(count.ToString());
}
You can use a linq query like this:
var count = flw.Controls.OfType<CheckBox>().Count(x=>x.Checked);
It returns count of CheckBox controls in flw which are checked.
Based on your comments and the edits to your question, you need to be looking for your CheckBoxes in the FlowLayoutPanel to which you added them, not groupBox. Given that your FlowLayoutPanel is called flw, do the following:
public void CountIt()
{
foreach (CheckBox box in flw.Controls.OfType<CheckBox>())
{
if (box.Checked)
{
count++;
}
}
MessageBox.Show(count.ToString());
}
Note that I'm increasing the count only when the CheckBox is checked, which is now reflected in your question. Failing to do that check was a bug in your original code.
I have a ListView with cascading checkboxes inside of it. What I would like to do is be able to uncheck all child boxes if the parent box is unchecked (and similarly I'd like to check all child boxes if the parent is checked). Currently, if I check or uncheck a box, the parent node and child nodes are greyed out, but the check mark is still visible on the child boxes.
I presume I'd have to do this recursively. I've given the following code a try and I think it should work, but it breaks at runtime due to casting issues.
private void listViewChildNodeModifier(ListViewItem item)
{
if (item.SubItems.Equals(null)) return;
else
{
foreach (ListViewItem childItem in item.SubItems)
{
listViewChildNodeModifier(childItem);
if(childItem.Tag is TestingNode)
((TestingNode)childItem.Tag).Enabled = item.Checked;
}
}
}
Could you not do this
foreach (ListViewItem item in this.ListView.Items)
{
for (int i = 0; i < item.SubItems.Count; i++)
{
item.SubItems[i].Checked = false;
//will something like this work for you let me know
}
}
another alternative which should work as well would be the following
foreach (ListViewItem.ListViewSubItem childItem in item.SubItems)
{
if(item.Checked)
{
item.Checked = false;
}
}
I've been searching for about an hour already and couldn't find a best solution.
I am migrating from VB.NET to C# Forms and to C# WPF.
Never mind that...
so I use this code for C# forms and it works, but not in C# WPF
if (ListView1.SelectedItems.Count > 0)
{
for (lcount = 0; lcount <= ListView1.Items.Count - 1; lcount++)
{
if (ListView1.Items[lcount].Selected == true)
{
var2 = lcount;
break;
}
}
}
this is the way I want to get the index of the item clicked in listbox.
I have the error in .SELECTED
please help.
You can get SelectedIndex from listView. No need to traverse over all items because as per your code you seems to be interested in index of any selected item.
var2 = ListView1.SelectedIndex;
OR
simply this will work if interested in only first index:
if (lst.SelectedItems.Count > 0)
{
var2 = lst.Items.IndexOf(lst.SelectedItems[0]);
}
If you are using the .NET Compact Framework, SelectedIndex is not supported. For a general solution, I prefer SelectedIndices:
ListView.SelectedIndexCollection indices = lst.SelectedIndices;
if (indices.Count > 0)
{
// Do something with indices[0]
}
For Visual Studio 2015, SelectedIndex does not seem to be available. Instead, you can use SelectedIndices[x] where x=0 will give you the first selected item:
listView.SelectedIndices[0]
You can also set the MultipleSelect property to false to only allow one item to be selected at a time.
It can return NULL. Also the SelectedIndexChanged event can be FIRED TWICE. And the first time, there nothing selected yet.
So the only safe way to find it is like this:
private void lv1_SelectedIndexChanged(object sender, EventArgs e)
{
if (lv1.FocusedItem == null) return;
int p = lv1.FocusedItem.Index;
... now int p has the correct value...
sColl.Clear();
string item = String.Empty;
if (listView1.SelectedItems.Count > 0) {
for (int i = 0; i < listView1.SelectedItems.Count; i++) {
if (listView1.SelectedItems[i].Selected) {
int i2 = listView1.SelectedItems[i].Index;
item = listView1.Items[i2].Text;
sColl.Add(item);
}
}
}
listView1.SelectedItems.Clear();
foreach (var itemS in sColl)
{
string items = itemS;
}
sColl.Clear();
listView1.SelectedItems.Clear();
Why don't bring back the SelectedIndex ? Add this extension after your current namespace.
public static class Extension
{
public static int SelectedIndex(this ListView listView)
{
if (listView.SelectedIndices.Count > 0)
return listView.SelectedIndices[0];
else
return 0;
}
}
Encapsulate this class in a namespace called Extensions and then add this inside your projects namespace to use the extension.
using Extensions;
Then simply use like this
private void ListView1_SelectedIndexChanged(object sender, EventArgs e)
{
int selectionindex = ListView1.SelectedIndex();
ListViewItem seletedItem = ListView1.Items[selectionindex];
}
P.S.
The extension method should have returned -1 on Else, but as long as you're using it from the SelectedIndexChanged event, you're fine as it won't get fired if there are no items.
This is by design, as the SelectedIndexChanged event gets fired twice. Once to deselect the initial item, then to select the new one.
Proper way is to return -1 and check for negative numer.
This is also why someone here got and ArgumentOutOfRange Exception.
I have a method that adds items to my listbox called refreshInterface which is called as soon as the programe starts, adding names of homeforms in the listbox using the FormItems class, here is the rereshInterface method below
public void refreshInterface()
{
//int number = 0;
foreach (DataSet1.xspGetAnalysisUsageTypesRow homeForms in myDataSet.xspGetAnalysisUsageTypes)
{
var forms = new FormItems(homeForms);
listBox1.Items.Add(forms);
}
}
The FormItems class is this below
public class FormItems
{
public DataSet1.xspGetAnalysisUsageTypesRow types { get; set; }
public FormItems(DataSet1.xspGetAnalysisUsageTypesRow usageTypes)
{
types = usageTypes;
}
public override string ToString()
{
// returns the rows that are relating to types.xlib_ID
var libtyps = types.GetxAnalysisUsageRows();
var cnt = 0;
foreach (DataSet1.xAnalysisUsageRow ty in libtyps)
{
//returns true if ty is null
bool typeNull = ty.Isxanu_DefaultNull();
// if its false, if xanu_Default is set
if (!typeNull)
{
cnt += 1;
}
}
var ret = String.Format("set {0} [Set: {1}]", types.xlib_Desc, cnt);
//return this.types.xlib_Desc;
return ret;
}
}
Each listbox (the listbox is on the left of the homeform) item has a number of reports that can be added to it, so for instance, i select an homeform from my listbox, there are 12 textboxes on the right hand side and each textbox has a pair of buttons which are Browse and Clear. If I click on the browse button a new form appears, and i select a report from that form and add it to a particular textbox, the count for that homeform should update, and i clear a textbox for a particular homeform, the count should also update.
At the moment when i debug the application, it shows me the count of each Homeform depending on the amount of reports added to the homeform, but while the programe is running, if i add a new report to a homeform, the count does not update until i restart the debug session. I was told about using a Databinding method but not sure of how i could use it here
How do i ge my listbox item to update ?
You should probably look into binding. Here is a good place to start:
http://www.codeproject.com/Articles/140621/WPF-Tutorial-Concept-Binding
If you want a GUI to respond to data changes then binding is your best friend.
You should bind List Box component source to Observable Collection, every update you do to Observable Collection will update List Box data.
Might not be exact but should give you an idea.
public void refreshInterface()
{
Dictionary<int,string> items = new Dictionary<int,string>();
//int number = 0;
foreach (DataSet1.xspGetAnalysisUsageTypesRow homeForms in myDataSet.xspGetAnalysisUsageTypes)
{
var formitem = new FormItems(homeForms);
items.Add(formitem.someprop, formitem.toString());
}
listbox.DataSource = items;
listbox.DisplayMember = "Value";
listbox.ValueMember = "Key";
}