I am trying to find the index of a particular value from the CheckedListBoxControl. The CheckedListBoxControl has a DataSource, DisplayMember, ValueMember set to a DataTable and two columns receptively. Now I have to set the CheckedState Property to true by finding its index from CheckedListBoxControl by using some value from the ValueMember and then calling the SetItemChecked() method with that index.
I'm not able to find any property or method which returns the index. Please help.
If a list box control is bound to a data source, you can iterate throught all listbox items using the the GetItem() method and the ItemCount property:
for(int i = 0; i < checkedListBoxControl.ItemCount; i++) {
object dataRow = checkedListBoxControl.GetItem(i);
}
To find the index of the specified item you can use the FindItem() method
searching by DisplayText:
string s = "searchString";
int index = checkedListBoxControl.FindItem(startIndex, true, delegate(ListBoxFindItemArgs e) {
e.IsFound = s.Equals(e.DisplayText);
});
searching by ValueMember:
object value = 100;
int index = checkedListBoxControl.FindItem(startIndex, true, delegate(ListBoxFindItemArgs e) {
e.IsFound = object.Equals(value, e.ItemValue);
});
Please also take a look at the "How to get checked rows of a data-bound CheckedListBoxControl" article.
Related
I am using GWT combobox with Select item (dropdown checkbox)
I want to make some items defaultly checked, but i cant find any solutions..
#Override
protected void success(List<warehouseDTO> t)
{
warehouse_list = t;
for (int i = 0; i < warehouse_list.size(); i++)
{
whl.put(warehouse_list.get(i).getId() + "", warehouse_list.get(i).getName());
}
selectItemMultiplePickList.setValueMap(whl);
selectComboForm.setItems(selectItemMultiplePickList);
}
On new "Article" (thing in warehouse) its good, but on edit i need to have checked by default.
Maybe its posible with setAttribute but cant find list of attributes.
Thanks
You should use the following:
setValues(values);
Here values accepts multiple String values.
Now as you're doing:
whl.put(warehouse_list.get(i).getId() + "", warehouse_list.get(i).getName());
your key for the combobox will be warehouse_list.get(i).getId() and value will be warehouse_list.get(i).getName().
So to show multiple values as selected values, you need to pass multiple warehouse_list.get(i).getId() as values.
For example, if you want show first 3 values as selected, you can do the following:
selectItemMultiplePickList.setValues(
warehouse_list.get(0).getId(),
warehouse_list.get(1).getId(),
warehouse_list.get(2).getId());
I've read all the similiar posts about this darn control (DataGridViewComboBoxCell) and setting it's value programmatically but implementing all the suggestions hasn't worked. I could probably change the UI to get around this problem but I don't like to be beat!
private void PopulateAreaForRoleAssociation()
{
// If businessRoleList is null then no data has been bound to the dgv so return
if (businessRoleList == null)
return;
// Ensure businessArea repository is instantiated
if (businessAreaRepository == null)
businessAreaRepository = new BusinessAreaRespository();
// Get a reference to the combobox column of the dgv
DataGridViewComboBoxColumn comboBoxBusinessAreaColumn = (DataGridViewComboBoxColumn)dgvBusinessRole.Columns["BusinessArea"];
// Set Datasource properties to fill combobox
comboBoxBusinessAreaColumn.DisplayMember = "Name";
comboBoxBusinessAreaColumn.ValueMember = "Id";
comboBoxBusinessAreaColumn.ValueType = typeof(Guid);
// Fill combobox with businessarea objects from list out of repository
comboBoxBusinessAreaColumn.DataSource = businessAreaRepository.GetAll();
// loop through the businessRoles list which the dgv is bound to and get out each dgv row based upon the current id in the loop
businessRoleList.Cast<BusinessRole>().ToList().ForEach(delegate(BusinessRole currentRole)
{
DataGridViewRow currentRowForRole = dgvBusinessRole.Rows.Cast<DataGridViewRow>().ToList().Find(row => ((BusinessRole)row.DataBoundItem).Id == currentRole.Id);
// Get a reference to the comboBox cell in the current row
DataGridViewComboBoxCell comboBoxCell = (DataGridViewComboBoxCell)currentRowForRole.Cells[2];
// Not sure if this is necessary since these properties should be inherited from the combobox column properties
comboBoxCell.DisplayMember = "Name";
comboBoxCell.ValueMember = "Id";
comboBoxCell.ValueType = typeof(Guid);
// Get the business area for the current business role
BusinessArea currentAreaForRole = businessAreaRepository.FetchByRoleId(currentRole.Id);
// if the role has an associated area then set the value of the cell to be the appropriate item in the combobox
// and update the cell value
if (currentAreaForRole != null)
{
foreach (BusinessArea area in comboBoxCell.Items)
{
if (currentAreaForRole.Id == area.Id)
{
comboBoxCell.Value = area.Id;
dgvBusinessRole.UpdateCellValue(2, comboBoxCell.RowIndex);
}
}
}
});
}
The dgv is first bound to a binding list holding BusinessRole objects, then the combobox column is bound to a basic list of BusinessArea objects that come out of a repository class. I then loop through the bindinglist and pull out the row of the dgv that is bound to the current item in the bindinglist loop.
With that row I make a database call to see if the BusinessRole entity is associated with a BusinessArea entity. If it is then I want to select the item in the combobox column that holds the BusinessAreas.
The problem is that when the grid is loaded, all the data is there and the comboboxes are populated with a list of available areas, however any values that are set are not displayed. The code that sets the value is definately getting hit and the value I am setting definately exists in the list.
There are no data errors, nothing. It's just refusing to update the UI with the value I programmatically set.
Any help would be greatly appreciated as always.
Thanks
This code works for my first combo box I have in my row with the following code, but I try it with the next one in the row and it doesn't work. I could use the help with the rest I have 3 more to do. I do set the combo boxes on a second form from this form with the same code as is on the last line of the try block but using the cell information instead of the dataset
try
{
string strQuery = "select fundCode from vwDefaultItems where IncomeType = '" + stIncome + "'";
SqlDataAdapter daDefault = new SqlDataAdapter(strQuery, conn);
DataSet dsDefault = new DataSet();
daDefault.Fill(dsDefault);
strDefFund = dsDefault.Tables[0].Rows[0].ItemArray[0].ToString();
dgvCheckEntry.Rows[curRow].Cells[7].Value = dsDefault.Tables[0].Rows[0].ItemArray[0].ToString();
}
catch (Exception eq)
{
}
I have a DataTable and when I alter (add,modifiy..ect) it wont reflect on the DataGrid which is bound to the DataTable.
ItemsSource="{Binding TableData,Mode=TwoWay,IsAsync=True}"
Thats the binding ^
Now when I set the RowError
TableData.Rows[x].RowError = ex.Message;
HasError gets set to true... but the DataGrid does not reflect this ( I have a style that marks a row red when there is an error)
Note: My changes are not being reflected on more then setting ErrorMessages, I've also tried adding rows in the ViewModel and those added rows are not relfected either.
About the DataTable:
It has no set columns or anything, it relfects a selected Database table which the user picks.
Binding to a DataTable won't work. You need to first convert your DataTable to an ObservableCollection<>. From here:
public void ConvertDataTable( DataTable dt )
{
DataList = new ObservableCollection<ProjectWorkHours>();
//Scan and arrange data into ObservableCollection
int UserID = 0;
if ( dt.Rows.Count >0 )
{
UserID = int.Parse( dt.Rows[0]["UserID"].ToString() );
//Distill project id list
List<int> ProjectIDList = GetProjectIDList( dt );
for ( int i = 0 ; i < ProjectIDList.Count; i ++ )
{
int ProjectID= ProjectIDList[i];
//Get WorkRecord
int[] MyWorkRecord = GetWorkRecord(dt, ProjectID);
ProjectWorkHours newProjectWorkHours = new ProjectWorkHours(UserID,ProjectID,MyWorkRecord);
DataList.Add( newProjectWorkHours);
}
}
}
The link has a more full example of working with a database and using binding.
What Type is TableData?
If it is a List<> then changing the items in the list will NOT update the binding
If it is an ObservableCollection<> then changing the items in the collection will update the binding
I've got my objects in PagedCollectionView bound to DataGrid and DataPager.
var pcView = new PagedCollectionView(ObservableCollection<Message>(messages));
How can I easily get items from current page in PagedCollectionView from my ViewModel? I wish there were something like this:
var messagesFromCurrentPage = pcView.CurrentPageItems; // error: no such a property
There are properties like SourceCollection, PageIndex and Count but I don't find them useful in this case. What am I missing here?
If you want to get select items you can just use Linq to do it.
var items = pcView.Where(i => i.SomeCondition == true);
Make sure you add a using statement for System.Linq.
Edit: Whenever I have a question as to what is really going on I just look at the code using Reflector (or ILSpy). In this case here is the relevant code inside GetEnumerator() which is how the Select or Where gets the items in the list:
List<object> list = new List<object>();
if (this.PageIndex < 0)
{
return list.GetEnumerator();
}
for (int i = this._pageSize * this.PageIndex; i < Math.Min(this._pageSize * (this.PageIndex + 1), this.InternalList.Count); i++)
{
list.Add(this.InternalList[i]);
}
return new NewItemAwareEnumerator(this, list.GetEnumerator(), this.CurrentAddItem);
So you can see how it is returning only the items in the current page from this code.
This article shows how to implement a copy operation on a drop event. I'd like to do the same but I want my dropped item to appear in the collection according to where it was placed on the UI. So I need the StartIndex much like on a NotifyCollectionChangedEventArgs when an ObservableCollection changes. In the article you'll see that eventually you get a SelectionCollection object whose items have an Index property. But unfortunately this is the index of the source collection (where it was picked) and not the destination collection (where it was dropped).
Ok, this is quite ugly, but I didn't find another way, not by myself and also not by searching the net for answers. Must have been another deadline at Microsoft that prevented the rather obvious functionality to be included...
Basically the method below does everything manually, getting the drop location and checking it for listbox items to use as index references.
private void ListBoxDragDropTarget_Drop(object sender, Microsoft.Windows.DragEventArgs e)
{
// only valid for copying
if (e.Effects.HasFlag(DragDropEffects.Copy))
{
SelectionCollection selections = ((ItemDragEventArgs)e.Data.GetData("System.Windows.Controls.ItemDragEventArgs")).Data as SelectionCollection;
int? index = null;
if (selections != null)
{
Point p1 = e.GetPosition(this.LayoutRoot); // get drop position relative to layout root
var elements = VisualTreeHelper.FindElementsInHostCoordinates(p1, this.LayoutRoot); // get ui elements at drop location
foreach (var dataItem in this.lbxConfiguration.Items) // iteration over data items
{
// get listbox item from data item
ListBoxItem lbxItem = this.lbxConfiguration.ItemContainerGenerator.ContainerFromItem(dataItem) as ListBoxItem;
// find listbox item that contains drop location
if (elements.Contains(lbxItem))
{
Point p2 = e.GetPosition(lbxItem); // get drop position relative to listbox item
index = this.lbxConfiguration.Items.IndexOf(dataItem); // new item will be inserted immediately before listbox item
if (p2.Y > lbxItem.ActualHeight / 2)
index += 1; // new item will be inserted after listbox item (drop location was in bottom half of listbox item)
break;
}
}
if (index != null)
{
foreach (var selection in selections)
{
// adding a new item to the listbox - adjust this to your model
(lbxConfiguration.ItemsSource as IList<ViewItem>).Insert((int)index, (selection.Item as ViewItem).Clone());
}
}
}
}
}