Clone a DataBound Checked List Box - c#

I have a DataBound CheckedListBox, I "check" few items on list box(source), then I need to clone it to new Checked List Box(target). It need to have all the data, with checked state. I have tried with following function. It is properly flowing through this function.
But finally I can see items on target CheckedListBox but none of the items in target is checked.
private void CloneCheckedListBox(CheckedListBox source, CheckedListBox target)
{
foreach (int checkedItemIndex in source.CheckedIndices)
{
target.SetItemChecked(checkedItemIndex, true);
}
}
Edit:
I have a User control which I have placed on a TabPage, on that User Control there is a "CheckedListBox", I do need to create a new TabPage with the user entered value on selected(current) TabPage(on User Control)
So, what I have done is, create a new Tab Page, get a Copy of the User Control calling it's "Clone()" method.
In "Clone()" method need to have CheckedListBox cloning feature.
Here is my Cloning Code, which is on User Control...
public SearchMain Clone()
{
SearchMain smClone = new SearchMain();
smClone.txtManufacturers.Text = this.txtManufacturers.Text;
smClone.udPriceFrom.Value = this.udPriceFrom.Value;
smClone.udPriceTo.Value = this.udPriceTo.Value;
smClone.chkOld.Checked = this.chkOld.Checked;
smClone.chkPrx.Checked = this.chkPrx.Checked;
smClone.chkDisc.Checked = this.chkDisc.Checked;
smClone.chkStock.Checked = this.chkStock.Checked;
smClone.chkFirstDes.Checked = this.chkFirstDes.Checked;
smClone.chkFirstPN.Checked = this.chkFirstPN.Checked;
smClone.txtSuppPN.Text = this.txtSuppPN.Text;
smClone.txtManuPN.Text = this.txtManuPN.Text;
smClone.txtManufacturers.Text = this.txtManufacturers.Text;
smClone.meDesAND.Text = this.meDesAND.Text;
smClone.meDesOR.Text = this.meDesOR.Text;
smClone.meDesNOT.Text = this.meDesNOT.Text;
smClone.lbManufacSelected.Items.AddRange(this.lbManufacSelected.Items);
smClone.lbSearchWithIn.Items.AddRange(this.lbSearchWithIn.Items);
**CloneCheckedListBox(this.clbLang, smClone.clbLang);**
// CloneCheckedListBox(this.clbTypes, smClone.clbTypes);
return smClone;
}

You can see correct answere here..
Programatically Checking DataBound CheckListBox

try set
source.DataSource = target.DataSource;
target.DisplayMember = "YourDisplayItem";
target.ValueMember = "YourValueItem";
foreach (int checkedItemIndex in source.CheckedIndices)
{
target.SetItemChecked(checkedItemIndex, true);
}

Related

Clicking on List Item on Dropdown

I'm having a problem in interacting with a custom dropdown control. It works fine the 1st 6 times, but after that, since the screen is resized, it could no longer locate and click the option in the dropdown control, returning an exception - can't click on hidden control. I tried putting in a itemField.DrawHighlight(); on the control I'm looking for, and it finds it, however it can't click on it. I also tried a to scroll down, but it seems to be not working.
bool addItemCheck = false;
int scrollCheck = 0;
while (Check == false)
{
var addItem= new HtmlButton(window);
addItem.SearchProperties.Add(HtmlButton.PropertyNames.Id, "add-new-item");
Mouse.Click(addItem);
scrollCheck = scrollCheck + 1;
if (scrollCheck > 6)
{
Mouse.MoveScrollWheel(window, -100);
}
var itemDropDown = new HtmlSpan(window);
itemDropDown .SearchProperties.Add(HtmlSpan.PropertyNames.Class, "item-dropdown");
itemDropDown .SearchProperties.Add(HtmlSpan.PropertyNames.InnerText, "Select an Item");
Mouse.Click(itemDropDown );
addItemCheck = itemDropDown.Exists;
}
bool itemBoxCheck = false;
HtmlCustom itemBox = null;
while (itemBoxCheck == false)
{
itemBox = new HtmlCustom(window);
itemBox.SearchProperties.Add(HtmlCustom.PropertyNames.Id, "item-listbox");
var itemField = new HtmlCustom(itemBox);
itemField .SearchProperties.Add(HtmlCustom.PropertyNames.InnerText, item);
Mouse.Click(itemField);
itemBoxCheck = itemBox.Exists;
}
I would really appreciate any help. Thank you.
Try calling the method InsureClickable() on the control before attempting to click on it.
for example:
itemDropDown.EnsureClickable();
Mouse.Click(itemDropDown);
Edit:
if this doesn't work you'll have to scroll down to the item.
try using:
Mouse.MoveScrollWheel()
if that doesn't work also you'll have to map the scroll control and click on it.

Combobox will not show the right item

I have used a combobox with items from a tabel from MySql which works fine. I can pick an item and save an object and the chosen object is shown. But if the user wants to edit the content I can't get the combobox to show the chosen item in the edit-window. The textboxes work fine but the combobox shows the first one in the list and not the selected item.
My constructor:
public CreateForm(Letter brev)
{
InitializeComponent();
this.brev = brev;
GetDropDownBoxReady();
saveButton.Visible = false;
deleteButton.Visible = false;
insertText(brev);
}
private void GetDropDownBoxReady()
{
fraByCB.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDown;
fraByCB.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
fraByCB.AutoCompleteSource = AutoCompleteSource.ListItems;
fraOmraadeCB.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDown;
fraOmraadeCB.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
fraOmraadeCB.AutoCompleteSource = AutoCompleteSource.ListItems;
}
public void insertText(Letter brev)
{
// these work fine
objekt1textBox.Text = brev.Object1;
objekt2TextBox.Text = brev.Object2;
diverse2TextBox.Text = brev.Diverse2;
portoTakstTextBox.Text = brev.PortoTakst;
portoTillægTextBox.Text = brev.PortoTillaeg;
portoFraTextBox.Text = brev.PortoFra.ToString("dd-MM-yyyy");
portoTilTextBox.Text = brev.PortoTil.ToString("dd-MM-yyyy");
// these don't
fraByCB.SelectedText = brev.FraBy;
fraOmraadeCB.SelectedItem = fraOmraadeCB.FindStringExact(brev.FraOmraade);
}
Let me know if you need more of the code too find the problem.
You says that you could see the Items in the combobox dropdown but there is no code shown above that fills the dropdown. Then, probably, you fill the Items property of the combobox with strings in the InitializeComponent call with predefined strings (Using the WinForms designer).
At this point the error is in the insertText method:
fraByCB.SelectedIndex = fraByCB.FindStringExact(brev.FraBy);
fraOmraadeCB.SelectedIndex = fraOmraadeCB.FindStringExact(brev.FraOmraade);
FindStringExact returns the position of the item searched if it is found, you could use this value to set the SelectedIndex property of the combos
So your actual code contains two erros. The first is about the fraByCB.SelectedText. This method is used to get/set the highlight on some or all of the text portion of the combo, not to select an intem. The second error is the assignement of the return value of FindStringExact (an integer) to the SelectedItem property that wants the string instead

C# ListView from Another Function

Please forgive me for such a stupid question. I am sure many of you will find this easy, where I have sent almost half the day reading trying to figure this out.
Here is the problem:
I have a FORM (Form1.cs) made. In that form I created a listview, and named it "ListView1".
Within the Form1.cs, I call a function called FileManager(this), where I pass in the THIS object.
In FileManager.cs I was able to listviewArray= originalForm.Controls.Find("listView1", true) and find that 'listview'.
When I do a listviewArray[0]<-- I can't seem to add a list to it.
FileManager.cs
FileManager(object sender)
{
if (sender != null)
{
originalForm = (Form)sender;
}
}
public void getFiles()
{
filePaths = Directory.GetFiles(hsocDir);
if(filePaths != null)
{
listviewArray= originalForm.Controls.Find("listView1", true);
if(listviewArray != null)
{
ListViewItem lvi = new ListViewItem("text");
// My Array is listViewArray
// How to add things to Lvi to it.
}
}
== Form1.cs
public Form1()
{
InitializeComponent(`enter code here`);
mysql = new MySQLCheck(this);
fileManager = new FileManager(this);
fileManager.getFiles();
}
You can't access element 0 of the collection because the collection is empty. To add an item, use:
listViewArray.Items.Add(lvi);
You need to modify the Items collection instead of the ListView itself for this to work, as ListView is not a collection (its a control).
listViewArray.Items.Add(lvi);
Also in your listview,setting this properties will help :
// Set the view to show details.
listViewArray.View = View.Details;
// Select the item and subitems when selection is made.
listViewArray.FullRowSelect = true;
// Display grid lines.
listViewArray.GridLines = true;

The BindingList Datasource of a Combobox refreshes correctly but the Combobox displays items in the wrong order

I have a BindingList< KeyValuePair < string, string > > that is bound to a ComboBox control. Based on some conditions, the BindingList will be added a new KeyValuePair. Now, the Newly added item shows up at index 0 of the Combobox, instead of at the end.
While debugging, I found that the BindingList has got the right order. (i.e, the new KeyValuePair is appended)
Also, I check the SelectedValue of the ComboBox in it's SelectedIndexChanged handler and it seems to be not of the ListItem that got selected. Instead, it is that of the supposed ListItem, if the ComboBox had got the right order as in its DataSource, - the BindingList..
The code is a small part of a large project.. Plz let me know if the question is not clear. I can put the relevant parts of the code as per our context.
How could something like this happen? What can I do differently?
I have this class something like this.
public class DropdownEntity
{
//removed all except one members and properties
private string frontEndName
public string FrontEndName
{
get {return this.frontEndName; }
set {this.frontEndName= value; }
}
//One Constructor
public DropdownEntity(string _frontEndName)
{
this.FrontEndName = _frontEndName;
//Removed code which initializes several members...
}
//All methods removed..
public override string ToString()
{
return frontEndName;
}
}
In my windows form, I have a tab control with several tabs. In one of the tabs pages, I have a DataGridView. The user is supposed to edit the cells and click on a Next - button. Then, some processing will be done, and the TabControl will be navigated to the next tab page.
The next tab page has the combobox that has the problem I mentioned. This page also has a back button, which will take back.. the user can modify the gridview cells again.. and click on the next button. This is when the order gets messed up.
I am posting here the Click event handler of the Next Button.. Along with the class, with the rest of the code removed.
public partial class AddUpdateWizard : Form
{
//Removed all members..
BindingList<KeyValuePair<string, string>> DropdownsCollection;
Dictionary<string, DropdownEntity> DropdownsDict;
//Defined in a partial definition of the class..
DataGridView SPInsertGridView = new DataGridView();
ComboBox DropdownsCmbBox = new ComboBox();
Button NextBtn2 = new Button();
Button BackBtn3 = new Button();
//Of course these controls are added to one of the panels
public AddUpdateWizard(MainForm mainForm)
{
InitializeComponent();
DropdownsDict = new Dictionary<string, DropdownEntity>();
}
private void NextBtn2_Click(object sender, EventArgs e)
{
string sqlArgName;
string frontEndName;
string fieldType;
for (int i = 0; i < SPInsertGridView.Rows.Count; i++)
{
sqlArgName = "";
frontEndName = "";
fieldType = "";
sqlArgName = SPInsertGridView.Rows[i].Cells["InsertArgName"].Value.ToString().Trim();
if (SPInsertGridView.Rows[i].Cells["InsertArgFrontEndName"].Value != null)
{
frontEndName = SPInsertGridView.Rows[i].Cells["InsertArgFrontEndName"].Value.ToString().Trim();
}
if (SPInsertGridView.Rows[i].Cells["InsertArgFieldType"].Value != null)
{
fieldType = SPInsertGridView.Rows[i].Cells["InsertArgFieldType"].Value.ToString().Trim();
}
//I could have used an enum here, but this is better.. for many reasons.
if (fieldType == "DROPDOWN")
{
if (!DropdownsDict.ContainsKey(sqlArgName))
DropdownsDict.Add(sqlArgName, new DropdownEntity(frontEndName));
else
DropdownsDict[sqlArgName].FrontEndName = frontEndName;
}
else
{
if (fieldType == "NONE")
nonFieldCount++;
if (DropdownsDict.ContainsKey(sqlArgName))
{
DropdownsDict.Remove(sqlArgName);
}
}
}
//DropdownsCollection is a BindingList<KeyValuePair<string, string>>.
//key in the BindingList KeyValuePair will be that of the dictionary.
//The value will be from the ToString() function of the object in the Dictionary.
DropdownsCollection = new BindingList<KeyValuePair<string,string>>(DropdownsDict.Select(kvp => new KeyValuePair<string, string>(kvp.Key, kvp.Value.ToString())).ToList());
DropdownsCmbBox.DataSource = DropdownsCollection;
DropdownsCmbBox.DisplayMember = "Value";
DropdownsCmbBox.ValueMember = "Key";
//Go to the next tab
hiddenVirtualTabs1.SelectedIndex++;
}
private void BackBtn3_Click(object sender, EventArgs e)
{
hiddenVirtualTabs1.SelectedIndex--;
}
//On Selected Index Changed of the mentioned Combobox..
private void DropdownsCmbBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropdownsCmbBox.SelectedValue != null)
{
if (DropdownsDict.ContainsKey((DropdownsCmbBox.SelectedValue.ToString())))
{
var dropdownEntity = DropdownsDict[DropdownsCmbBox.SelectedValue.ToString()];
DropdownEntityGB.Text = "Populate Dropdowns - " + dropdownEntity.ToString();
//Rest of the code here..
//I see that the Datasource of this ComboBox has got the items in the right order.
// The Combobox's SelectedValue is not that of the selected item. Very Strange behavior!!
}
}
}
}
The very first time the user clicks the Next Button, it's fine. But if he clicks the Back Button again and changes the Data Grid View cells.. The order will be gone.
I know, it can be frustrating to look at. It's a huge thing to ask for help. Any help would be greatly appreciated!
Please let me know if you need elaboration at any part.
Thanks a lot :)
I think you have two problems here.
First, if you want to retain the order of the items you should use an OrderedDictionary instead of a regular one. A normal collection will not retain the order of the items when you use Remove method. You can see more info about this related to List here.
You could use such dictionary like this:
DropDownDict = new OrderedDictionary();
// Add method will work as expected (as you have it now)
// Below you have to cast it before using Select
DropDownCollection = new BindingList<KeyValuePair<string, string>>(DropDownDict.Cast<DictionaryEntry>().Select(kvp => new KeyValuePair<string, string>(kvp.Key.ToString(), kvp.Value.ToString())).ToList());
The second problem could be that you change the display name (FrontEndName) of already existing items, but the key is preserved. When you add a new item, try to remove the old one that you're not using anymore and add a new item.
The Sorted Property of the Combobox is set to True! I didn't check that until now. I messed up. Terribly sorry for wasting your time Adrian. Thanks a lot for putting up with my mess here.. :)

c# how do i refresh items in my listbox

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

Categories

Resources