Dynamically search listbox using textbox in C# - c#

I have a database with some devices in it and I want to be able to dynamically search in my listbox, when typing in my textbox.
I tried some other suggestions on StackOverflow:
Dynamic Search Result C#
So far I have this:
List<Device> devices = new List<Device>();
private void UpdateBindings()
{
deviceFoundListbox.DataSource = devices;
deviceFoundListbox.DisplayMember = "FullInfo";
}
private void searchTextbox_TextChanged(object sender, EventArgs e)
{
DataAccess database = new DataAccess();
devices = database.GetDevice(searchTextbox.Text);
lock(lockObject)
{
lastChange = DateTime.Now;
textChanged = true;
}
}
private void dynamicSearchTimer_Tick(object sender, EventArgs e)
{
lock(lockObject)
{
if(textChanged && lastChange > DateTime.Now.AddSeconds(-2))
{
UpdateBindings();
textChanged = false;
lastChange = DateTime.Now;
}
}
}
However, I can't seem to get it to work.
Any help's appreciated!
EDIT: The Device class:
internal class Device
{
public string DeviceName { get; set; }
public string SerialNumber { get; set; }
public string LoanStatus { get; set; }
public string Initials { get; set; }
public string FullInfo
{
get
{
return $"Device: {DeviceName} S/N: {SerialNumber} Loaner Status: {LoanStatus} Initials: {Initials}";
}
}
}

Result has been assigned to "device" and you are updating "devices" to DataSource?
How to assign :
device = database.GetDevice(searchTextbox.Text);
What return database.GetDevice();
If you have a device declaration when you add the devices list? or are you add device to devices?
You can use basically use devices.Add(database.GetDevice());

Related

Displaying Item from Listbox onto Textbox

I am trying to display an item from a CSV file onto listbox(this part works) and then display individual parts of that item in separate labels.
public partial class InventoryForm : Form
{
public InventoryForm()
{
InitializeComponent();
}
public List<ItemsList> itemsLists(string csvPath)
{
var query = from l in File.ReadAllLines(csvPath)
let data = l.Split('|')
select new ItemsList
{
Name = data[0],
Type = data[1],
DMGTyp = data[2],
DMG = data[3],
Weight = int.Parse(data[4]),
Price = int.Parse(data[5]),
Description = data[5]
};
return query.ToList();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog filePath = new OpenFileDialog();
filePath.ShowDialog();
textBox1.Text = filePath.FileName;
}
private void btnLoad_Click(object sender, EventArgs e)
{
listBox1.DataSource = itemsLists(textBox1.Text);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//to do show individual pieces in labels
}
public class ItemsList
{
public string Name { get; set; }
public string Type { get; set; }
public string DMGTyp { get; set; }
public string DMG { get; set; }
public int Weight { get; set; }
public int Price { get; set; }
public string Description { get; set; }
}
}
The items are broken up into 6 parts and the list box only shows the name of the item but I want the label to show the rest of the item's properties. Any clues on how to do that?

C# winform ComboBox

I have a combo box on a C# Winform that I would like to populate with the string name variables from this list, nothing else. Here is the list code.
class Animals
{
public string averageMass { get; set; }
public string lifeSpan { get; set; }
public string whereToFind { get; set; }
public string name { get; set; }
public string animalImage { get; set; }
}
class Mammals:Animals
{
public static List<Mammals> MammalList = new List<Mammals>();
public string hairColour { get; set; }
}
You can do this on Combobox:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem == "Mammals") //You can also do index e.g. comboBox1.SelectedIndex == 0
{
comboBox2.DataSource = mammalList;
}
else
{
comboBox2.DataSource = reptileList;
}
}
Or you can also do this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox2.DataSource = fncGetSpecies(comboBox1.SelectedIndex);
}
private string[] fncGetSpecies(int intIndex)
{
//This will return if selected item is 0 which is Mammals or 1 if the selected item is Reptiles.
return intIndex == 0 ? mammalList : reptileList;
}
You can set DataSource of ListBox2 based on selection from ListBox1's within SelectedIndexChanged event handler as follow:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(listBox1.SelectedIndex==0)//Which is Mammals list
{
listBox2.DataSource = reptileList;
}
else//Which is Reptiles list
{
listBox2.DataSource = mammalList;
}
}
You can add string items to combobox using following code
combobox.Items.Add(stringItem);

Binding combobox BindingList Winforms C#

Ok, so I have been facing this issue several times now but I always seemed to figure it out.
This time, ive been stuck and ive tried multiple things, but nothing is working.
I have a combobox of customers in a customer form. When i create a new customer, my combobox is not updating. It only refreshes when closing and re-opening the form.
I am aware of the "ugly and quick" solutions, but I don't want to use this unless I have no other choise. So ive been using BindingLists because of the events... BUT this is not working in my case.
Ive been staring to this for a time now, let it aside, tried again, but keep on failing.
Does anyone know whats missing in this puzzle?
Now the code: Presenter
public class CustomerPresenter
{
private tbl_customer customer = new tbl_customer();
private CustomerView customerView = new CustomerView();
public CustomerPresenter(tbl_customer customer, CustomerView customerView)
{
this.customer = customer;
this.customerView = customerView;
customerView.customerPresenter = this;
}
// Get a list of customers
public List<tbl_customer> customerList;
public BindingList<tbl_customer> getCustomers()
{
using (var customers = new DBCrownfishEntities())
{
var customer = from c in customers.tbl_customer
where c.IsDeleted == false
select c;
this.customerList = customer.ToList();
var listBinding = new BindingList<tbl_customer>(this.customerList);
return listBinding;
}
}
public void testAdd()
{
tbl_customer customer = new tbl_customer();
customer.CustomerPrefix = "Pref";
customer.CustomerName = "Name";
customer.CustomerAddress = "Address";
customer.CustomerPostalCode = "1111";
customer.CustomerCity = "City";
customer.CustomerCountry = "Country";
customer.CustomerCountryCode = "BE";
customer.CustomerVat = "123456789";
customer.hasVatNumber = true;
try
{
using (var cust = new DBCrownfishEntities())
{
cust.tbl_customer.Add(customer);
cust.SaveChanges();
MessageBox.Show("A new customer is succesfully added!");
}
}
catch (EntityException exception)
{
MessageBox.Show(exception.InnerException.Message.ToString(), "Error Connecting database");
}
catch (Exception)
{
throw;
}
}
}
View:
BindingSource bsCustomers = new BindingSource();
private void CustomerView_Load(object sender, EventArgs e)
{
bsCustomers.DataSource = customerPresenter.getCustomers();
cbCustomers.DataSource = bsCustomers;
cbCustomers.DisplayMember = "CustomerName";
cbCustomers.ValueMember = "CustomerId";
radioButton1_CheckedChanged(null, null);
}
private void button1_Click_1(object sender, EventArgs e)
{
customerPresenter.testAdd();
}
Model:
public partial class tbl_customer
{
public tbl_customer()
{
this.tbl_invoices = new HashSet<tbl_invoices>();
}
public int CustomerID { get; set; }
public string CustomerPrefix { get; set; }
public string CustomerName { get; set; }
public string CustomerEmailaddress { get; set; }
public string CustomerAddress { get; set; }
public string CustomerPostalCode { get; set; }
public string CustomerCity { get; set; }
public string CustomerVat { get; set; }
public string CustomerCountryCode { get; set; }
public string CustomerCountry { get; set; }
public bool IsDeleted { get; set; }
public bool hasVatNumber { get; set; }
public virtual ICollection<tbl_invoices> tbl_invoices { get; set; }
}

Subset List of parent List not binding to Listbox in Winforms

I am trying to bind a List of a custom class to a Listbox and cannot get anything to display. The List is a subset of another List. I can bind the parent List and see the items, but not the child List. How can I get the subset List to bind to the Listbox? I have tried changing the order of the ListBox's DisplayMember, ValueMember, and DataSource properties. In debugging I can see that the DataSource has the correct values, but I can't get them to display. Relevant code below:
public class DimZone
{
public int Zone_Key { get; set; }
public int Zone_ID { get; set; }
public int Facility_Key { get; set; }
public string Zone_Name { get; set; }
public string Zone_Type { get; set; }
}
GlobalVariables Class containing global List collection:
public static List<DimZone>[] zoneCollection = new List<DimZone>[maxServerCount];
Form using global List collection and subset List:
List<DimZone> zoneCollectionAppended = new List<DimZone>();
private void StaffStatusReportForm_Load(object sender, EventArgs e)
{
facilityComboBox.DataSource = GlobalVariables.facilityCollection;
GetFacilityIndex();
CreateZoneAppendedList();
PopulateUI();
}
private void CreateZoneAppendedList()
{
foreach (var zone in GlobalVariables.zoneCollection[currentFacilityIndex])
{
if (zone.Zone_Name != "All")
{
zoneCollectionAppended.Add(zone);
}
}
}
private void PopulateUI()
{
if (zoneCollectionAppended != null)
{
zoneListBox.DisplayMember = "Zone_Name";
zoneListBox.ValueMember = "Zone_ID";
zoneListBox.DataSource = zoneCollectionAppended;
}
}
Your code contains various unclear parts. In any case, the best proceeding in these situations is setting up a properly-working simpler code and modifying it until reaching the stage you want. I can provide this properly-working first step. Sample code:
private void Form1_Load(object sender, EventArgs e)
{
List<DimZone> source = new List<DimZone>();
DimZone curZone = new DimZone() { Zone_Key = 1, Zone_ID = 11, Facility_Key = 111, Zone_Name = "1111", Zone_Type = "11111" };
source.Add(curZone);
curZone = new DimZone() { Zone_Key = 2, Zone_ID = 22, Facility_Key = 222, Zone_Name = "2222", Zone_Type = "22222" };
source.Add(curZone);
zoneListBox.DisplayMember = "Facility_Key";
zoneListBox.DataSource = source;
}
public class DimZone
{
public int Zone_Key { get; set; }
public int Zone_ID { get; set; }
public int Facility_Key { get; set; }
public string Zone_Name { get; set; }
public string Zone_Type { get; set; }
}
Try this code and confirm that the changes in zoneListBox.DisplayMember (e.g., "Zone_Key", "Zone_ID", etc.) are immediately reflected in the values being displayed by zoneListBox.
The problem was I was changing zoneListBox.DataSource from one source to another on load, which caused the error. In order for the DataSource to update properly, I had to set zoneListBox.DataSource = null before updating to a new DataSource. I don't know why I have to set it to null first, but it solved my problem. So my updated code is as follows:
private void PopulateUI()
{
if (zoneCollectionAppended != null)
{
zoneListBox.DisplayMember = "Zone_Name";
zoneListBox.ValueMember = "Zone_ID";
//DataSource had to be reset to null before updating to new DataSource
zoneListBox.DataSource = null;
zoneListBox.DataSource = zoneCollectionAppended;
}
}

Add new Item to the listbox from other window

In my wpf application, I've created two view classes, DayView and CustomView. In DayView, there is a listbox consist of some entries. In listbox, there is stackpanel with 5 textboxes. In my CustomView class, also I've created stackpanel with 5 textboxes. when I enter data into those textboxes of CustomView and click on save button,the new entry should create and data should saved in respective textboxes of DayView.
CustomView class:
namespace TimeSheet
{
/// <summary>
/// Interaction logic for CustomView.xaml
/// </summary>
public partial class CustomView : Window
{
public List<Harvest_Project> projectList { get; set; }
public List<Harvest_Client> clientList { get; set; }
public Harvest_Project selectedProjectid { get; set; }
public Harvest_Client selectedClientid { get; set; }
private string client { get { return ClientText.Text; } set { ClientText.Text=value;} }
private string application { get { return ApplicationText.Text; } set { ApplicationText.Text = value; } }
private string starttime { get { return StartTimeText.Text; } set { StartTimeText.Text = value; } }
private string stoptime { get { return StopTimeText.Text; } set { StopTimeText.Text = value; } }
private string task { get { return TaskText.Text; } set { TaskText.Text = value; } }
private string project { get { return ProjectText.Text; } set { ProjectText.Text = value; } }
public CustomView()
{
InitializeComponent();
this.DataContext = this;
Globals._globalController.setCustomViewWindow(this);
clientList = Globals._globalController.harvestManager._CLIENTLIST;
projectList = Globals._globalController.harvestManager._PROJECTLIST;
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
if (sender is Harvest_TimeSheetEntry)
{
//Harvest_TimeSheetEntry entry = new Harvest_TimeSheetEntry();
//if (!entry.isSynced)
//{
// entry.ClientNameBinding = client;
// entry.ApplicationNameBinding = application;
// entry.StartTimeBinding = starttime;
// entry.StopTimeBinding = stoptime;
// entry.TaskNameBinding = task;
// entry.ProjectNameBinding = project;
//}
Globals._globalController.getDayViewWindow.Show();
this.Hide();
}
}
private void ClientComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = (sender as ComboBox).SelectedItem.ToString();
}
private void ProjectComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = (sender as ComboBox).SelectedItem.ToString();
}
}
}
I don't understand, how should i save this data in DayView listbox. Please suggest some ways.!
This is DayView window
[1]: http://i.stack.imgur.com/1Qi0e.png
This is CustomView window!
[2]: http://i.stack.imgur.com/mACxR.png
In my opinion it's more suitable to use an mvvm Framework to make your solution more structured, and then use a Messenger to make communication between your views.

Categories

Resources