I'm having trouble adding items to a list box.
For whatever reason, I can't get the item to display in the list box (nothing is displayed.)
private void btnPressForCandy_Click(object sender, EventArgs e)
{
txtcandyMachine.Text = "";
avalibleCandy = avalibleCandy - 1;
candyDisplay.Items.Add("Candy"); //Key Line
}
Has anyone got any suggestions as to what I'm doing wrong?
Thanks in advance guys.
Joe
I've just realised that there's some other code effecting the list box.
private List <Candy> CollectedCandy;
Which is why possibly it wasn't working.
CollectedCandy = new List<Candy>();
However I'm not quite sure what I need to add to get this to work.
Obviously I need to call UpdateCandyDisplay but beyond that I'm not sure.
private void UpdateCandyDisplay()
{
candyDisplay.Items.Clear();
foreach (Candy candy in CollectedCandy)
{
candyDisplay.Items.Add("Candy");
}
}
try this
namespace WindowsFormsApplication11
{
public partial class Form1 : Form
{
List<string> _items = new List<string>(); // <-- Add this
public Form1()
{
InitializeComponent();
_items.Add("One"); // <-- Add these
_items.Add("Two");
_items.Add("Three");
listBox1.DataSource = _items;
}
}
}
and more information use this link How might I add an item to a ListBox?
I've just realised that there's some other code effecting the list box.
private List <Candy> CollectedCandy;
Which is why possibly it wasn't working.
CollectedCandy = new List<Candy>();
However I'm not quite sure what I need to add to get this to work.
Obviously I need to call UpdateCandyDisplay but beyond that I'm not sure.
private void UpdateCandyDisplay()
{
candyDisplay.Items.Clear();
foreach (Candy candy in CollectedCandy)
{
candyDisplay.Items.Add("Candy");
}
}
Related
Hello I have to make this gui below and add items to the listbox states during runtime.
I have been able to make this code below which list 10 states to the second listbox. But for the first listbox I have to be able to add the states to the list at runtime, I have no idea how to do this. Can anyone please help me to solve this?
private void button1_Click(object sender, EventArgs e)
{
for(int i = 1; i <= 10; i++)
{
listTenStates.Items.Add(listStates.Items[listStates.Items.Count - i]);
}
}
I'll give this a general answer. But you should read the site's guides.
The public Form1() method executes at run time. You can add items to a list box after InitializeComponent(); like this:
statesList.Items.Add("State 1");
///and so on
statesList.Items.Add("State 50");
or like this
listBox1.Items.AddRange(new string[] { "state 1", "state 50" });
Assuming you have all states as string inside the list, you can add those to your listStates as described below
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
List<string> states = new List<string>() { "State1", "state2" };//This should contain all the states
foreach (var state in states)
{
listStates.Items.Add(state);
}
}
}
Say I have a list called listOfFruits in my main form. In a second form I've made I want the user to be able to remove items from that list to a second list called removedFruits. Currently I know I can access these lists in my second form simply passing them as parameters in the form constructor. However c# can't do pointers (correct?) so how can I effect the main form's copy of these lists from my second form? Because currently any changes to those lists in my second form don't effect the main form's original copy of the lists. If I were to remove 5 fruits from the listOfFruits passed to my second form then after finishing my work the main form would still still have a full listOfFruits and an empty removedFruits. Is there a simple fix to this? Maybe a get/set or a way to add/remove items from the original lists from the second form? Maybe the answer is in some sort of accessor stuff?
EDIT: To clarify; I want to add to one list, and remove from another. Not add/remove to the same list. Not sure if this matters entirely but I figured I'd be specific here in case it does.
EDIT2: I think the issue is I'm copying the original list from the first form and not editing it directly. Can someone fix my code so I can access the original list from my second form instead of making a copy of the list?
public partial class ListSelector : Form
{
private string windowName = Form1.typeOfModuleAdded;
public List<IOModule> innerIOList;
IOModule cardAdded = null;
public ListSelector(List<IOModule> cardList)
{
this.Text = windowName;
innerIOList = cardList;
InitializeComponent();
InitializeList();
}
private void InitializeList()
{
if (windowName == "Drive")
{
string[] listDrives = { "ACS880", "test" };
listBox1.Items.AddRange(listDrives);
}
else if (windowName == "IOBlock")
{
if (!innerIOList.Any())
{
MessageBox.Show("No cards loaded! Please import cards from IO List.", "Error Empty Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
foreach (IOModule card in innerIOList)
{
cardAdded = card;
listBox1.Items.Add(card.name);
}
}
else if (windowName == "Local Card")
{
string[] listLocals = { "1756-EN2T", "test" };
listBox1.Items.AddRange(listLocals);
}
else if (windowName == "Processor")
{
string[] listProcessors = { "1756-L71S", "test" };
listBox1.Items.AddRange(listProcessors);
}
}
private void addBtn_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
Form1.SetModule(listBox1.SelectedItem.ToString());
Form1.confirmedAdd = true;
this.Close();
}
else if (cardAdded != null)
{
innerIOList.Remove(cardAdded);
}
else
{
MessageBox.Show("No module selected!");
}
}
and here's how I pass the list to that form from my first form:
ListSelector test = new ListSelector(ioList);
test.ShowDialog();
where ListSelector is the name of my second form, and ioList is the list im passing to it.
EDIT3: added more code
"However c# can't do pointers (correct?) so how can I effect the main form's copy of these lists from my second form?"
No, not correct. Any object reference (for instance, of a List<Fruit>) is still very much a pointer to a place in memory, and if you pass the same List<Fruit> object to both Forms, they share the same List.
I don't know why your changes to your listOfFruits don't chow up in your first Form. I would check the following things:
Are you 100% sure you use the same List<Fruit> object in both Forms. (If you create a new List like this: new List<Fruit>(listOfFruits) it is NOT the same List)
Does the first Form have any way of finding out, that the List has changed? Possible using a Timer with recurring checks, or (my favorite) triggering an event when you change something, and subscribe an EventHandler in the first Form to the event.
I assume that you have created a second list in your second form that is filled with the items of the first form's list. Then changes on the second list aren't reflected in the first list. You have to use the same reference of the list.
public Form2(List<Fruit> listOfFruits)
{
this._listOfFruits = listOfFruits;
}
private List<Fruit> _listOfFruits;
Instead using a public field, try to use property and on creating your new ListSelector pass the list to the property.
public partial class ListSelector : Form
{
private string windowName = Form1.typeOfModuleAdded;
private List<IOModule> innerIOList;
IOModule cardAdded = null;
public List<IOModule> CardList
{
get
{
return innerIOList;
}
set
{
innerIOList = value;
InitializeList();
}
}
public ListSelector()
{
this.Text = windowName;
InitializeComponent();
}
When creating your new ListSelector object
ListSelector ls = new ListSelector();
ls.CardList = your mainform list of IOModule here
ls.ShowDialog();
See the linked screenshot below.
In short, I need those little white boxes to disappear - they're supposed to house an image, but there is no image, and so I'd rather they disappear.
I've accomplished this using the follow code:
foreach (ToolStripMenuItem menuItem in mnuMain.Items)
((ToolStripDropDownMenu)menuItem.DropDown).ShowImageMargin = false;
This works for what I guess are the main items, but not the sub-items, as you can see in the picture.
I've tried a few variations on the above code to try and get it to capture everything instead of just the first level items, but no luck.
What am I doing wrong?
http://i.imgur.com/bst1i4v.png
You should do that for sub items too. To do so, you can use this code:
private void Form1_Load(object sender, EventArgs e)
{
SetValuesOnSubItems(this.menuStrip1.Items.OfType<ToolStripMenuItem>().ToList());
}
private void SetValuesOnSubItems(List<ToolStripMenuItem> items)
{
items.ForEach(item =>
{
var dropdown = (ToolStripDropDownMenu)item.DropDown;
if (dropdown != null)
{
dropdown.ShowImageMargin = false;
SetValuesOnSubItems(item.DropDownItems.OfType<ToolStripMenuItem>().ToList());
}
});
}
This is a modified version of above. Use:
MainMenuStrip.HideImageMargins();
Because the recursive method performs the intended manipulation, I used overloading to make it clearer what is intended. Pattern matching is used because the above sample will throw an exception, not return null.
public static void HideImageMargins([NotNull] this MenuStrip menuStrip)
{
HideImageMargins(menuStrip.Items.OfType<ToolStripMenuItem>().ToList());
}
private static void HideImageMargins([NotNull] this List<ToolStripMenuItem> toolStripMenuItems)
{
toolStripMenuItems.ForEach(item =>
{
if (!(item.DropDown is ToolStripDropDownMenu dropdown))
{
return;
}
dropdown.ShowImageMargin = false;
HideImageMargins(item.DropDownItems.OfType<ToolStripMenuItem>().ToList());
});
}
I am working on a c# program where there is a CheckedListbox host_listbox.
In my code I have a option for adding new items to the checkedlistbox. When am done adding the new item I can't see the newly added item in my checkedlistbox till the program is closed and run again.
I have tried
Refresh()
BeginUpdate()
EndUpdate()
but they are not working.
When adding new item is done, it is showing the newly added item in the ITEMS of checkedlistbox, it is not being displayed though.
Can anyone suggest me some alternative way to make it work?
public static void fill_checkboxlist()
{
host_listbox.Items.Clear();
host_listbox.BeginUpdate();
foreach (KeyValuePair<string, host_config> hlitem in host_list)
{
string sitem = hlitem.Key;
if (host_list[sitem].sessionOptions == null)
host_list[sitem].sessionOptions = new SessionOptions();
host_list[sitem].sessionOptions.Protocol = Protocol.Sftp;
host_list[sitem].sessionOptions.HostName = host_list[sitem].ip;
host_list[sitem].sessionOptions.UserName = host_list[sitem].username;
host_list[sitem].sessionOptions.Password = host_list[sitem].password;
host_list[sitem].sessionOptions.PortNumber = Convert.ToInt32(host_list[sitem].port);
//host_list[sitem].sessionOptions.SshHostKeyFingerprint = host_list[sitem].rsa;
host_listbox.Items.Add(hlitem.Key.ToString(), false);
}
host_listbox.Refresh();
}
You forgot to add this command at the end of your method:
host_listbox.EndUpdate();
When you call fill_checkboxlist() form XXXX_Load method, it will not work when you omit this line. I also do not think you absolutely need to call the Refresh method...
If you still have problems, try to check this:
In your XXXXX.Designer.cs file look at #region Windows Form Designer generated code. There you will see generated code and there may be something you do not see and is causing your problems. There should be something like this:
//
// host_listbox
//
this.host_listbox.FormattingEnabled = true;
this.host_listbox.Location = new System.Drawing.Point(33, 36);
this.host_listbox.Name = "host_listbox";
this.host_listbox.Size = new System.Drawing.Size(179, 169);
this.host_listbox.TabIndex = 0;
EDIT:
Your method should not be static!
Try to modify your method like this and see what happens.
public void fill_checkboxlist()
{
host_listbox.Items.Clear();
host_listbox.BeginUpdate();
host_listbox.Items.Add("A", false);
host_listbox.Items.Add("B", false);
host_listbox.Items.Add("C", false);
host_listbox.EndUpdate();
}
If you think it needs to be static, you must do it like this:
private void Form1_Load(object sender, EventArgs e)
{
fill_checkboxlist(host_listbox);
}
public static void fill_checkboxlist(CheckedListBox chlb)
{
chlb.Items.Clear();
chlb.BeginUpdate();
chlb.Items.Add("A", false);
chlb.Items.Add("B", false);
chlb.Items.Add("C", false);
chlb.EndUpdate();
}
Also I do not understand, why is your method marked as public....
Im relatively new to programming and still learning. I have just made a calculator, and then I got the idea that I wanted to save the two input numbers (value1, value2) and the result in a datagridview in another winform.
First of i added a button (bSave) for saving it.
My first attempt was with:
dgvSavedResults.Rows.Add(tbValue1.Text, tbValue2.Text, tbResult.Text);" and works OK.
My next attempt was to save all of it in another class:
public class Information
{
private string value1;
private string value2;
private string result;
public string Value1
{
get { return value1; }
set { value1 = value; }
}
public string Value2
{
get { return value2; }
set { value2 = value; }
}
public string Result
{
get { return result; }
set { result = value; }
}
}
And in the calculator form it looks like this when i click the save button:
private void bSave_Click(object sender, EventArgs e)
{
Information info = new Information();
info.Value1 = tbTal1.Text;
info.Value2 = tbTal2.Text;
info.Result = tbResultat.Text;
}
I think i need to use a datatable and the loop through whats inside the Information-class.
But i have really no idea how to make this work. I have googled around but i havent found something that i understand. Am i on the right track? Or am i totally wrong with my thinking?
If anyone could take the time to explain to me what to do and maybe show me an example how to do it would be really appreciated. Thanks
You can have a list of your results:
BindingList<Information> resultsList = new BindingList<Information>();
Bind it to DataGridView using BindingSource:
BindingSource resultsBindingSource = new BindingSource();
this.resultsBindingSource.DataSource = resultsList;
this.dgvSavedResults.DataSource = this.resultsBindingSource ;
then:
private void bSave_Click(object sender, EventArgs e)
{
Information info = new Information();
info.Value1 = tbTal1.Text;
info.Value2 = tbTal2.Text;
info.Result = tbResultat.Text;
resultsList.Add(info);
}
And it's done.
Also, depending on how you want to add columns, you can do it manually, or you can generate it automatically from public properties of your Information class:
dgvSavedResults.AutoGenerateColumns=true;
EDIT:
to properly reflect changes on your datagridview, its better to use BindingList instead of List