ListBox Items Disappear - c#

I currently have a ListBox (called wafersListBox) bounded to an ArrayList of a certain object type (called wafers). When I want to add to the ListBox dynamically, I use the following code:
wafersListBox.DataSource = null;
wafersListBox.DataSource = wafers;
wafersListBox.Refresh();
This successfully changes the items in the ListBox, but all of the items disappear (they're still there and can be selected, but the user just can't see them).
Any ideas on how to fix this?
UPDATE:
This is my Wafer class:
public class Wafer
{
public string maID;
public string MID
{
get
{
return maID;
}
set
{
maID = value;
}
}
public Wafer(string m)
{
maID = m;
}
}
This is the code that I call, it adds a copy of the currently selected item to the listbox:
Wafer w = wafersListBox.SelectedItem as Wafer;
wafers.Add(w);
wafersListBox.DataSource = null;
wafersListBox.DisplayMember = "MID";
wafersListBox.DataSource = wafers;
wafersListBox.Refresh();

You should probably tell the wafersListBox what property to use as it's caption.
Do it like this;
wafersListBox.DisplayMember = "PropertyNameThatYouWantToShow";

Sorry - I'm not able to add an additional comment, which would have been preferable over writing a new "answer" but do you see any difference if you switch the position of the lines as below?
Wafer w = wafersListBox.SelectedItem as Wafer;
wafers.Add(w);
wafersListBox.DataSource = null;
wafersListBox.DataSource = wafers;
wafersListBox.DisplayMember = "MID";
wafersListBox.Refresh();
One other thing I just came across on a different SO posting (ListBox doesn't show changes to DataSource):
"There is also a bug in the list box which can cause this problem. If you set the SelectionMode to None this problem appears.
As a work around I set the selection mode to One and then back to None when updating the datasource."

Related

Panel Does not update TreeView

I have a TreeView that is displayed inside a panel. The data in the TreeView is based on data returned from the database. The first time, the data is correct. The second time, the TreeView is not refreshed, and the previous data is still showing in the tree. I checked the list that contain the data. The list returned the correct data. I've Google the issue, and could not resolved it with some of the answers that were posted. Here is a sample code of how the TreeView is being created and added to the Panel.
ReportGroups gr = new ReportGroups();
var Name = gr.GetReportName(groupID);
TreeView tr = new TreeView();
tr.BeginUpdate();
tr.Size = new Size(570, 600);
tr.Name = "Home";
tr.Nodes.Add("Reports Name");
tr.CheckBoxes = true;
if (Name.Count() > 0)
{
foreach (var item in Name)
{
if (item != null)
{
tr.Nodes[0].Nodes.Add(item.reportName);
}
}
}
tr.Nodes[0].ExpandAll();
tr.EndUpdate();
this.pDisplayReportName.Width = tr.Width * 2;
this.pDisplayReportName.Height = 300;
this.pDisplayReportName.Controls.Add(tr);
this.pDisplayReportName.Refresh();
What am I doing wrong?
try to add this.pDisplayReportName.Clear(); so data will not double up. :)
The easy option would be to use this.pDisplayReportName.Controls.Clear(); just after tr.EndUpdate();. But, this would cause an issue if you have other controls within the same Panel.
The best option would be to use this.pDisplayReportName.Controls.RemoveByKey("MyTree"); instead of this.pDisplayReportName.Controls.Clear();
And, another option would be to add a TreeView in design time (with name tr) rather than dynamically to the panel. Then, use tr.Nodes.Clear(); before tr.BeginUpdate(); and remove following two lines from your code.
TreeView tr = new TreeView();
.
.
.
this.pDisplayReportName.Controls.Add(tr);
Cheers

Listview Add Items not appearing C#

I'm working on a small program as part of my A Level Computing course that is designed to track orders. It is written in C# using the Windows Forms.
I am having an issue where I enter all the information for a new order and then press OK and it should update the ListView with the information. I have my ListView in Detail view with 4 columns but nothing ever gets added to the ListView. The section of code that should add the items to the ListView is being executed and is not throwing any errors or causing the program to crash but nothing is being added. Its weird because I am using the exact same method that I used in my little prototype mock up but for some reason now it is not working.
All the things I've found on here or on the internet seem to suggest its an issue with the View mode of the ListView and I've tried modifying this property to no avail.
Any ideas why this section of code is refusing to add anything to the ListView?
//Create an array to store the data to be added to the listbox
string[] orderDetails = { Convert.ToString(id + 1), rNameBox.Text, dateBox.Value.ToString(), orderBox.Text };
//DEBUGGING
Console.WriteLine(orderDetails[0]);
Console.WriteLine(orderDetails[1]);
Console.WriteLine(orderDetails[2]);
Console.WriteLine(orderDetails[3]);
//END DEBUGGING
//Add the order info to the ListView item on the main form
var listViewItem = new ListViewItem(orderDetails);
ths.listView1.Items.Add(listViewItem);
If you need any more information just say. Apologies if this is in the wrong format or something this is my first time here.
Your problem is that your ListViewItem contains a string array and it has no useful way of displaying it.
What you should be doing (there are a number of ways of doing this, but here's one) is creating a class, OrderDetail, with an Id, a Name, a Date, and so on. Give it a ToString() method (public override string ToString()) which returns what you want to display, e.g.:
public override string ToString()
{
return this.Name;
}
Create an instance of OrderDetail and set its properties. Create ListViewItem giving it the OrderDetail instance and add to the ListView. Repeat for as many OrderDetail instances you want.
Cheers -
Added: code which works:
int id = 12;
string rNameBoxText = "rName";
DateTime dateBoxValue = DateTime.Now;
string orderBoxText = "order";
string[] orderDetails = { Convert.ToString(id + 1), rNameBoxText, dateBoxValue.ToString(), orderBoxText };
//DEBUGGING
Console.WriteLine(orderDetails[0]);
Console.WriteLine(orderDetails[1]);
Console.WriteLine(orderDetails[2]);
Console.WriteLine(orderDetails[3]);
//END DEBUGGING
this.listView1.Columns.Clear();
this.listView1.Columns.Add("Id");
this.listView1.Columns.Add("rName");
this.listView1.Columns.Add("Date");
this.listView1.Columns.Add("Order");
this.listView1.View = View.Details;
//Add the order info to the ListView item on the main form
var listViewItem = new ListViewItem(orderDetails);
this.listView1.Items.Add(listViewItem);

Programmatically select a specific TreeViewItem into an unbound TreeView

In the code behind of my Silverlight application, I have the need to re-populate the TreeView and then make a specific TreeViewItem selected.
The code itself is pretty simple, here it is (i'll trim and pseudo-code-ify it to make it as short as possible)
private void Button_Click()
{
Guid idToSelect = TellMeWhatToSelect();
List<myObject> myDataList = myObjectRepository.RetrieveData().ToList();
myTreeView.Items.Clear();
foreach(myObject o in myDataList)
{
myTreeView.Items.Add(new TreeViewItem() { Content = o.DataField, Tag = o.Id });
}
myTreeView.Items.First(o => ((Guid)(o as TreeViewItem).Tag).Equals(idToSelect)).IsSelected = true;
}
That's basically it: i'm reading some data into myDataList, then i cycle through it and create as many TreeViewItems as needed in order to display the data.
Problem is, myTreeView.SelectedItem is null at the end of this, and SelectionChanged event isn't triggered. I would think that, since Items collection has been cleared and re-filled, switching IsSelected on one of the items would act like clicking, but it seems it doesn't).
Oddly enough (for me at least), issuing myTreeView.Items.First().IsSelected = true; by itself (that is, calling a method with that single line of code inside) works as expected: SelectedItem is there and all events are fired appropriateyl.
What's wrong with my code and/or what am I missing ? Looks like cleaning items up kind of breaks something.
I'm fairly sure others have had similar issues, but a bunch of searches I tried didn't help (most of the info & questions I came up with are WPF-related).
Thanks for your time, I'll provide more info if needed. Also, sorry for the wall of text.
UPDATE
Modifying code like this, now the method works as expected.
private void Button_Click()
{
Guid idToSelect = TellMeWhatToSelect();
List<myObject> myDataList = myObjectRepository.RetrieveData().ToList();
myTreeView.Items.Clear();
foreach(myObject o in myDataList)
{
myTreeView.Items.Add(new TreeViewItem() { Content = o.DataField, Tag = o.Id });
}
Dispatcher.BeginInvoke(()=>
{
myTreeView.Items.First(o => ((Guid)(o as TreeViewItem).Tag).Equals(idToSelect)).IsSelected = true;
});
}
Set property IsSelected inside of Dispatcher.BeginInvoke.
I had the same problem a while ago, I've solved by calling the UpdateLayout method from the treeview before setting the TreeViewItem as selected.Like this:
myTreeView.UpdateLayout();
myTreeView.Items.First(o => ((Guid)(o as TreeViewItem).Tag).Equals(idToSelect)).IsSelected = true;

How to disable only the checkboxes (and not the full checkedboxlist) of devexpress?

In non-edit mode, I need the user to be able to browse the list (scroll etc.) but not be able to select the checkboxes.
If I do checkedboxlist.enabled = false, then the whole list becomes disabled. Only I need to disable checkboxes so that user doesn't interact (in edit way) in non-edit mode.
EDIT
I just assign the list of strings to the checkedboxlist's datasource.
this.UserSelectedMsgTypes.DataSource = userSelectedMsgs;
this.UserAvailableMsgTypes.DataSource = availableMsgTypeList;
currently enabling/disabling whole list by doing
this.UserSelectedMsgTypes.Enabled = true/false;
this.UserAvailableMsgTypes.Enabled = true/false;
I tried #James solution earlier, doesnt work. Because somehow the 'ItemCount' is 0 even though there are items. in the datasource it shows that there are 6 items, but in list it shows 0.
Try this:
foreach (DevExpress.XtraEditors.Controls.CheckedListBoxItem item in checkedListBoxControl1.Items)
{
item.Enabled = false;
}
It's a bit of a dirty work around but how about this?
private IEnumerable<DevExpress.XtraEditors.Controls.CheckedListBoxItem> GetCheckItems(string[] myStringArray)
{
foreach(string s in myStringArray)
{
DevExpress.XtraEditors.Controls.CheckedListBoxItem item = new DevExpress.XtraEditors.Controls.CheckedListBoxItem();
item.Description = s;
yield return item;
}
}
Call with:
checkedListBoxControl1.Items.AddRange(GetCheckItems(new string[] {"test1","test2","test3"}).ToArray());
Then apply the first answer with the foreach loop (or set the ENabled = false in the GetCheckItems method).

Unselect all rows in datagridview

I have two datagridviews, and when I click to one of them, I would like to deselect all selection in the second datagridview, I tried this, but nothing works:
firstItemsDataGridView.ClearSelection();
firstItemsDataGridView.CurrentCell = null;
not working,
firstItemsDataGridView.ClearSelection();
if (firstItemsDataGridView.Rows.Count > 0)
firstItemsDataGridView[1, 0].Selected = true;
firstItemsDataGridView.CurrentCell = null;
firstItemsDataGridView.ClearSelection();
foreach (DataGridViewRow item in firstItemsDataGridView.Rows) {
item.Selected = false;
foreach (DataGridViewCell itemCell in firstItemsDataGridView.Columns) {
itemCell.Selected = false;
}
}
not working,
firstItemsDataGridView.Rows[0,-1].Selected = true;
not working too.
I have set selecting mode to full row selection, and I have no idea how to achieve my goal. thanks a lot!
dataGridView1.ClearSelection();
Should work. Maybe you have code that auto selects rows which is triggered?
An answer at NullSkull solved the problem for me which was that the cell at row 0, column 0 for the datagridview control was always selected on form load, and could not be deselected despite calling ClearSelection within the form's constructor method. I just had to call ClearSelection in the Form_Load event.
http://www.nullskull.com/q/10066166/how-to-deselect-the-first-row-when-the-form-i-loaded-in-datagridview-in-windows-application.aspx
Since there is no answer, and I used this answer in other posts and i ran into the same issue of first row being selected and deselecting wasn't possible:
Color blue = ColorTranslator.FromHtml("#CCFFFF");
Color red = ColorTranslator.FromHtml("#FFCCFF");
Color letters = Color.Black;
foreach (DataGridViewRow r in datagridIncome.Rows)
{
if (r.Cells[5].Value.ToString().Contains("1")) {
r.DefaultCellStyle.BackColor = blue;
r.DefaultCellStyle.SelectionBackColor = blue;
r.DefaultCellStyle.SelectionForeColor = letters;
}
else {
r.DefaultCellStyle.BackColor = red;
r.DefaultCellStyle.SelectionBackColor = red;
r.DefaultCellStyle.SelectionForeColor = letters;
}
}
This is a small trick, the only way you can see a row is selected, is by the very first column (not column[0], but the one therefore). When you click another row, you will not see the blue selection anymore, only the arrow indicates which row have selected.
SOLUTION:
i found out why my first row was default selected and found out how to not select it by default.
By default my datagridview was the object with the first tab-stop on my windows form. Making the tab stop first on another object (maybe disabling tabstop for the datagrid at all will work to) disabled selecting the first row
Just use:
dgvName.ClearSelection();
I tried this and it's working for me:
for (int i = 0; i < dataGridView1.Rows.Count;i++)
{
dataGridView1.Rows[i].Selected = false;
}
Make sure all the rows are deselected (dataGridView.Rows[...].Selected = false)
Row zero defaults to selected, so set dataGridView.Rows[0].Selected = false when opening the DataGridView and as long as the other options are set so the user can't select, then you will have, and maintain, nothing selected.
// no selection in dgv at the begening
dgv.FirstDisplayedCell = null;
dgv.ClearSelection();
// try this it is working !
If your using WPF and want to maintain a MVVM design pattern you can bind both selected items to the same property so when you select one the other will automatically be deselected.
try something like this
public class SingletonClass
{
private static SingletonClass _Instance;
public static SingletonClass Instance
{
get
{
if (_Instance == null)
_Instance = new SingletonClass();
return _Instance;
}
} // End Property Instance
private object _SelectedItem;
public object SelectedItem
{
get { return _SelectedItem; }
set { _SelectedItem = value; }
} // End Selected Item
}
<DataGrid Name="Datagrid1" SelectedItem="{Binding Source={x:Static Const:SingletonClass.Instance},Path=SelectedItem,IsAsync=True}">
<DataGrid Name="Datagrid2" SelectedItem="{Binding Source={x:Static Const:SingletonClass.Instance},Path=SelectedItem,IsAsync=True}">
*I only used a singleton class because this will work across different views in different instances, you can use a regular class if your in the same view.
Please note the IsAsync=True on the xmal, if you plan on using a singleton class across diffrent views it will not work without it.
As said #Taw in subcomments to top answer - "Don't call it too soon!".
In my case default behavior not works at all. My case - datagrid in tab of tabControl and it did not work if that tab not shown before!
That hack works like a charm :
AnyTabControl.SelectedTab = FirsTab;
gridModules.ClearSelection(); //placed at first tab
AnyTabControl.SelectedTab = SecondTab; //that tab i would like to show first
As a result : second tab displayed to user, and when he clicked to first - selection will not appear.

Categories