Get index with value in Checked List Box - c#

I am actually finding that chkContactType.Items is empty when I step through the code. I even added a Watch to chkContactType.Items.Count and it is never anything but 0. I am severly confused now as it obviously isn't as my Insert method works fine which uses these same boxes and inserts the Value Member for each item....
I have some checked list box controls that I need to set the CheckState based on the item value as that is what is stored in the DB for an exsiting record. Unfortunately, I only see a way to set this by index which is not stored. The index is local to the control so, for example, control ContactType has 15 items in it. Index is 0-14. Item Value is 39,40,41,42,43,44,45,46,47,48,49,50,2077,2078,2079 respectively. How can I either get the index value with the Value Member value OR set the checkstate of each returned item with the Value Member value?
Thanks
private void PaintDetails(Guid cNoteID)
{
var cNoteDetailDT = CurrentCaseNote.GetCNoteDetail(cNoteID);
LoadCaseNoteDetailData(cNoteDetailDT.Rows[0]);
// Load Contact Type Data for this CaseNote
// contactTypeDT returns ItemID of chk items
// that were checked for this Guid
using (var contactTypeDT = CurrentCaseNote.GetCNoteContactType(cNoteID))
{
if (contactTypeDT.Rows.Count > 0)
foreach (DataRow row in contactTypeDT.Rows)
{
LoadContactTypeData(row);
}
}
}
private void LoadContactTypeData(DataRow row)
{
// This does not work
var theItem = row["ItemID"].ToString();
// itemIndex always ends up set to -1
var itemIndex = chkContactType.Items.IndexOf(theItem);
chkContactType.SetItemChecked((int) itemIndex, true);
// This works I just need to supply the correct index
chkContactType.SetItemChecked(0,true);
}
EDIT in response to comment
This is how I populate the Checked ListBox. I know there is a "magic number" there. I am working on it. It relates to the CategoryID in the DB of ContactType.
// Contact Type Check List Box
chkContactType.DataSource = CurrentCaseNote.GetMaintItems(1);
chkContactType.DisplayMember = "ItemDescription";
chkContactType.ValueMember = "ItemID";
and then CurrentCaseNote BLL(kinda)-->
public static DataTable GetMaintItems(int iCat)
{
IQueryable<tblCaseNotesMaintItem> tItems = CaseNoteDAL.GetCNTable();
return (tItems.Where(item => item.CategoryID == iCat & item.IsActive).OrderBy(
item => item.OrderID).Select(item => new {item.ItemID, item.ItemDescription})).CopyLinqToDataTable();
}
and finally the DAL -->
public static Table<tblCaseNotesMaintItem> GetCNTable()
{
return dcCaseNotes.GetTable<tblCaseNotesMaintItem>();
}
EDIT 2
This is what my code NOW looks like but still no go. It is like ItemCount is never populated....
// Load Contact Type Data for this CaseNote
using (var contactTypeDT = CurrentCaseNote.GetCNoteContactType(cNoteID))
{
if (contactTypeDT.Rows.Count > 0)
foreach (DataRow row in contactTypeDT.Rows)
{
LoadContactTypeData(row);
}
}
}
private void LoadContactTypeData(DataRow row)
{
// This does not work
var theItem = row["ItemID"];
for (int i = 0; i < chkContactType.ItemCount; i++)
{
if(theItem == chkContactType.GetItemValue(i))
chkContactType.SetItemChecked(i,true);
}
}

This seems to work:
int index = checkedListBox1.Items.IndexOf("42");
checkedListBox1.SetItemChecked(index, true);

For j As Integer = 0 To chklst_distributorlist.Items.Count - 1
If chklst_distributorlist.GetItemText(chklst_distributorlist.Items.Item(j)) = ds1.Tables(0).Rows(0)("suppliername").ToString Then
chklst_distributorlist.SetSelected(j, True)
chklst_distributorlist.SetItemCheckState(j, CheckState.Checked)
End If
Next

I also faced the same issue.
The index of checkedListBox1.Items.IndexOf("value"); is always -1.
I managed to get the index using following code.
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (((System.Data.DataRowView)(checkedListBox1.Items[i])).Row.ItemArray[0].ToString() == "Value")
checkedListBox1.SetItemCheckState(i, CheckState.Checked);
}

Related

How do I delete a datarow from a datarow array?

I am looping through a array of datarows and when a particular random item is not valid I want to remove that item and get the new total to get another random item.
But when I delete a datarow the datarow does not go away... And yes there is probably a much better way to do this but I am not smart enough to do it..
Instead of removing the row I see this inside
ItemArray = podLps[1].ItemArray threw an exception of type System.Data.RowNotInTableException
//PHASE 1: Get all LPs in the pod and add to collection
List<DataRow> allLps = dtLp.AsEnumerable().ToList();
DataRow[] podLps = allLps.Where(x => x.ItemArray[0].ToString() == loPod).ToArray();
//PHASE 2: Pick a random LP from collection that has valid WAVE1
for (int i = podLps.Count(); i > 0; i--)
{
//Recount items in collection since one may have been removed
int randomIndex = random.Next(podLps.Count());
var randomLpUserId = podLps[randomIndex].ItemArray[1].ToString();
var randomLpWave1 = int.Parse(podLps[randomIndex].ItemArray[2].ToString());
//Get WAVE1 # for selected LP
lpNumberOfLoans = GetNumberOfLoans(session, randomLpUserId);
//check if LP has valid WAVE1 then use this person
if (randomLpWave1 > lpNumberOfLoans)
{
return randomLpUserId;
}
else
{
podLps[randomIndex].Delete();
}
}
look at this example and it should point you in the right direction for removing rows I just tested it and it works
for (int i = myDataTable.Rows.Count - 1; i >= 0; i--)
{
DataRow row = myDataTable.Rows[i]; //Remove
if (myDataTable.Rows[i][0].ToString() == string.Empty)
{
myDataTable.Rows.Remove(row);
}
}
I would suggest to use a List for podLps instead of an array.
Then you can use .RemoveAt as Jaco mentioned (dosn't work for arrays).
DataRow.Delete() just flags the Row to be deleted in the next update of your DataTable.
The easiest method is to convert your array of DataRow[] to a List, call RemoveAt and then convert the list back to an array:
var dest = new List<>(podLps);
dest.RemoveAt(randomIndex);
podLps = dest.ToArray();

C# NetSuite WebServices: Get value from custom field in saved search (ItemSearchAdvanced)

I'm using C# MVC to connect to NetSuite using their WebServices API. I have some current code that calls a saved search of inventory items. Here is the current code that is working perfectly:
ItemSearchAdvanced searchItems = new ItemSearchAdvanced();
searchItems.savedSearchId = "128";
SearchResult result = netSuiteSvc.search(searchItems);
int totalRecords = 0;
int processedRecords = 0;
UpdateNetsuitePriceListModel returnObj = new UpdateNetsuitePriceListModel();
returnObj.NewPriceList = new List<NetSuitePriceListRecord>();
if (result.status.isSuccess)
{
SearchRow[] searchRows = result.searchRowList;
if (searchRows != null && searchRows.Length >= 1)
{
for (int i = 0; i < searchRows.Length - 1; i++)
{
ItemSearchRow itemRow = (ItemSearchRow)searchRows[i];
if (itemRow.basic.itemId != null && itemRow.basic.mpn != null && itemRow.basic.basePrice != null && itemRow.basic.salesDescription != null)
{
returnObj.NewPriceList.Add(new NetSuitePriceListRecord()
{
ItemId = itemRow.basic.itemId[0].searchValue,
ManufacturerPartNumber = itemRow.basic.mpn[0].searchValue,
ContractPrice = Convert.ToDecimal(itemRow.basic.basePrice[0].searchValue),
Cost = CalculateProductCostForIngram(Convert.ToDecimal(itemRow.basic.basePrice[0].searchValue)),
Description = itemRow.basic.salesDescription[0].searchValue
});
processedRecords++;
}
totalRecords++;
}
}
else
{
throw new Exception("NetSuite Part List Blank");
}
}
else
{
throw new Exception("NetSuite Part List Search Failure");
}
Now I have need to pull the itemId from a custom added field rather than the default itemId field.
Obviously since this is a custom field it isn't a property of ItemSearchRowBasic. It looks like instead of the property I can choose "customFieldList" which is an array of "SearchColumnCustomField". If I choose an index for the array I can see that SearchColumnCustomField contains:
customLabel
internalId
scriptId
I imagine I should be able to get the internalId of the SearchColumnCustomField and somehow use that to get the search value for that custom column but I've had some trouble finding any examples that fit so far.
This custom field is a free form text field added to all inventory items.
Try setting scriptId with the ID of the field ("custitem_xyz"). That should work.
Before 2013 one would use internalId, but since then it changed to scriptId.
You would need to loop over the CustomRecord items in the customFieldList. I then usually check for a specific type so I can cast to the correct object, but with some reflection you could probably avoid that.
foreach (Record r in mySearchResponse.recordList){
foreach (CustomFieldRef cr in ((CustomRecord)r).customFieldList){
if (cr.GetType().Name == "SelectCustomFieldRef"){
if (((SelectCustomFieldRef)cr).scriptId == "my_custom_field"){
internalID = ((CustomRecord)r).internalId;
}
}
}
}

UsedRange.RowCount is not updated after an insert

I'm trying to write an Extension methods that adds a generic Item T to the workbook, I've got problem since the UsedRange.RowCount is not incremented after InsertMethod is called
public static RowItem<T> AddItem<T>(this SpreadsheetGear.IWorksheet worksheet, T item) where T : class
{
int currentRow = worksheet.UsedRange.RowCount;
//int currentRow = worksheet.UsedRange.RowCount;
RowItem<T> newItem = new RowItem<T>
{
Item = item,
RowIndex = currentRow
};
var reflected = item.GetType().GetProperties();
for (int i = 0; i < reflected.Length; i++)
{
object value = reflected[i].GetValue(item);
worksheet.Cells[currentRow, i].Value = value;
}
worksheet.UsedRange.Insert(SpreadsheetGear.InsertShiftDirection.Down);
worksheet.WorkbookSet.CalculateFull();
return newItem;
}
public static IEnumerable<RowItem<T>> AddItems<T>(this SpreadsheetGear.IWorksheet worksheet, IEnumerable<T> items) where T : class
{
var lst = new List<RowItem<T>>();
foreach (var item in items)
{
var newItem = AddItem<T>(worksheet, item);
lst.Add(newItem);
}
return lst;
}
It's always 1 ...what am I doing wrong? my dummy class is
public class Dummy
{
public string Desciption { get; set; }
public double Value { get; set; }
public DateTime Data { get; set; }
}
And I add items as
using (var _ = new WorkbookViewLock(workbookView1))
{
var worksheet = workbookView1.ActiveSheet.Workbook.Worksheets[0];
worksheet.AddItem<Dummy>(dummy);
worksheet.AddItem<Dummy>(dummy2);
}
If you are starting out with a blank worksheet (are you?), then it would make sense that the first two checks you make to worksheet.UsedRange.RowCount in your code would have a value of 1.
This is because the UsedRange of a blank worksheet will always be A1, which would correspond to a UsedRange.RowCount value of 1. That accounts for a value of 1 for your first AddItem(...) call.
The second AddItem(...) call is now looking at a worksheet that is populated with data, but still only 1 row since you've only added a single Dummy object at this point.
If you were to add a third Dummy object, you would see that the UsedRange increments to a value of 2.
FYI: You might have an additional issue with with your worksheet.UsedRange.Insert(...) line, since this will insert the number of rows that UsedRange currently consists of. It seems to me that if you are adding just a single Dummy object with this extension method, you should only insert, at most, one row...and that depends on where you want each new Dummy row to get added to the worksheet--the top or bottom of the used range. If you are inserting the new Dummy object at the top of the UsedRange, you should only apply Insert(...) on the top row of the UsedRange. If you are inserting the new Dummy object at the bottom of the UsedRange, no Insert(...) call is necessary at all since there's nothing below the UsedRange to shift down.

Wild Card Search in Listbox in C#

In my C# window application I need wild card search on list box.
i.e If I write some text in textbox it should be auto selected in that list box.
List box is binding using datatable e.g lstVendor.datasource = l_dtTable
Findstring() function is finding match only for starting string. But I need if match find at any position in particular text then it should be highlighted.
I am Using below code but not getting index/or even lstVendor.selecteditem = "string" not working.
Indexof() always return -1
string final = "";
foreach (Object lstItem in lstVendor.Items)
{
string s = ((DataRowView)(lstItem)).Row.ItemArray[0].ToString();
if (s.ToLower().Contains(txtVendor.Text.ToLower()))
{
int i = lstVendor.Items.IndexOf(s);
final += s + ",";
}
}
string[] l_strArrVendorList = final.TrimEnd(',').Split(',');
for (int Counter = 0; Counter < l_strArrVendorList.Length; Counter++)
{
lstVendor.SelectedItem = l_strArrVendorList[Counter];
}
Searching may return multiple matched items, this code will find the first matched items:
var firstMatched = listBox1.Items.Cast<DataRowView>()
.Where(v=>Convert.ToString(v.Row[0]).ToLower()
.Contains(txtVendor.Text.ToLower()))
.FirstOrDefault();
if(firstMatched != null) listBox1.SelectedItem = firstMatched;
You can remove the FirstOrDefault() to get the list of matched items and implement some navigation through the matched items.
For VS 2000 support, you have to use this extension class:
public static class EnumerableExtension {
public static IEnumerable<T> Cast<T>(this System.Collections.IEnumerable source){
foreach(var item in source)
yield return (T)item;
}
}
My code above should work OK for you, but looks like you just want your code to be fixed instead, here is the fixed code for you:
//Note that you need to set SelectionMode for your listBox like this:
lstVendor.SelectionMode = SelectionMode.MultiSimple;
foreach (var lstItem in lstVendor.Items.Cast<DataRowView>()) {
string s = lstItem.Row.ItemArray[0].ToString();
if (s.ToLower().Contains(txtVendor.Text.ToLower())) {
lstVendor.SelectedItems.Add(lstItem);
}
}

Adding to columns based on length

I have a ListView with two columns, Boxes and Files. I'm adding items to a list of strings, and then populating the ListView with that list of strings. I want to make it so all items that are 8 characters long go into the Boxes column and all items that are 9 characters go into the Files column. So far, I've tried to iterate through using a for loop and utilize an if else statement to add the items, but I seem to be doing something wrong. Here's my current code:
public void PopulateItemsList()
{
BoxAndFileList.Items.Clear();
ScanIdBox.Text = string.Empty;
for (int i = 0; i < BoxNumberRepository._boxAndFileList.Count; i++)
{
var item = BoxNumberRepository._boxAndFileList.Item[i];
if (item.Length == 8)
{
BoxAndFileList.Items.Insert(0, item);
}
else
{
BoxAndFileList.Items.Insert(1, item);
}
}
}
I'm iterating through my list (_boxAndFileList) and trying to utilize Insert() to insert items into the specific index of the columns (Boxes is 0, Files is 1). I can clearly see that Item is a legitimate property of a string list, yet VS keeps saying that list contains no definition of it. How can I go about doing this? And also, I haven't received outside feedback on this way of doing things yet, so if there's a better way, please let me know.
Edit: BoxNumberRepository is a class that news up a list called _boxAndFileList. Code below:
public class BoxNumberRepository : Scan_Form
{
public static List<string> _boxAndFileList = new List<string>();
public void AddItem(string item)
{
_boxAndFileList.Add(item);
}
public void Delete(string item)
{
_boxAndFileList.Remove(item);
}
public IEnumerable<string> GetAllItems()
{
return _boxAndFileList;
}
}
Thanks to Alessandro D'Andria for that suggestion. That was correct. However, all the items are still just adding to the first column, even if they're 9 characters. How can I get 9 character items to add to the second column?
The problem that you are having is that you have to add both the box and file to the list item at the same time.
EDIT: Changed cartesian product to a left outer join.
EDIT: Added comments and fixed a syntax bug
private List<string> _boxAndFileList = new List<string> { "12345678", "123456789", "1234", "123456778" };
public void PopulateItemsList()
{
//clear the list
BoxAndFileList.Items.Clear();
//add the labels to the top of the listbox
BoxAndFileList.Columns.Add("Boxes");
BoxAndFileList.Columns.Add("Files");
//set the view of the list to a details view (important if you try to display images)
BoxAndFileList.View = View.Details;
//clear scan id box
ScanIdBox.Text = string.Empty;
//get all the items whos length are 8 as well as a unique id (index)
var boxes = _boxAndFileList.Where(b => b.Length == 8).Select((b, index) => new { index, b }).ToList();
//get all the items whos length are NOT 8 as well as a unique id (index)
var files = _boxAndFileList.Where(f => f.Length != 8).Select((f, index) => new { index, f }).ToList();
//join them together on their unique ids so that you get info on both sides.
var interim = (from f in files
join b in boxes on f.index equals b.index into bf
from x in bf.DefaultIfEmpty()
select new { box = (x == null ? String.Empty : x.b), file = f.f });
//the real trick here is that you have to add
//to the listviewitem of type string[] in order to populate the second, third, or more column.
//I'm just doing this in linq, but var x = new ListViewItem(new[]{"myBox", "myFile"}) would work the same
var fileboxes = interim.Select(x => new ListViewItem(new []{ x.box, x.file})).ToArray();
//add the array to the listbox
BoxAndFileList.Items.AddRange(fileboxes);
//refresh the listbox
BoxAndFileList.Refresh();
}
Your _boxAndFileList is a List<string> so you should be declare item as string type instead var type:
string item = BoxNumberRepository._boxAndFileList.Item[i];
All your code should be like this:
public void PopulateItemsList()
{
BoxAndFileList.Items.Clear();
ScanIdBox.Text = string.Empty;
for (int i = 0; i < BoxNumberRepository._boxAndFileList.Count; i++)
{
string item = BoxNumberRepository._boxAndFileList.Item[i];
if (item.Length == 8)
{
BoxAndFileList.Items.Insert(0, item);
}
else
{
BoxAndFileList.Items.Insert(1, item);
}
}
}

Categories

Resources