There is a way to get all items selected with the mouse in a list view when virtual mode is enabled for this winform.
Example of an working code in use, I can retrieve only one selected file for now. Not too much examples finded on the web and could be identified as duplicate but is not conclusive for me, or the answer is to simple.
private void FilesFoundList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
{
try
{
if (e.ItemIndex >= 0 && e.ItemIndex < ListFilesInfos.Count)
{
try
{
var acc = ListFilesInfos[e.ItemIndex];
//with colors
e.Item = new ListViewItem(new string[] { acc.TagItem, acc.FileName, acc.FilePath.ToString() })
{ Tag = acc,
BackColor = SearchLabColor(0, Path.GetExtension(acc.FileName.ToString()), acc.FilePath.ToString(), acc.FileName.ToString()),
ForeColor = SearchLabColor(1, Path.GetExtension(acc.FileName.ToString()), acc.FilePath.ToString(), acc.FileName.ToString()),
UseItemStyleForSubItems = false
}; // Set Tag object property to our actual AccountInfo object
}
catch { this.Refresh(); }
}
}
catch
{
}
}
private void ShowItemsVirtual(List<SearchFilesInfo> infos)
{
try
{
FilesFoundList.VirtualListSize = infos.Count; // Set number of items in list view
}
catch { this.Refresh(); }
}
private void FilesFoundList_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (FilesFoundList.VirtualMode == true)
{
SelectedFiles.GlobalVar = (e.Item.SubItems[2]).Text.ToString() + (e.Item.SubItems[1]).Text.ToString();
}
}
You could abbreviate your code to:
List<multiSearchSelect> multiSearchSelect = new List<multiSearchSelect>();
private void FilesFoundList_VirtualItemsSelectionRangeChanged(object sender, ListViewVirtualItemsSelectionRangeChangedEventArgs e)
{
if (FilesFoundList.VirtualMode == true)
{
multiSearchSelect=
FilesFoundList.SelectedIndices
.Select(i=> new multiSearchSelect()
{
fileName = FilesFoundList.Items[i].SubItems[1].Text,
filePath = FilesFoundList.Items[item].SubItems[2].Text
});
}
}
class multiSearchSelect
{
public string fileName { set; get; }
public string filePath { set; get; }
}
I will post my solution that fits to my purpose. I have added ItemsSelectionRangeChanged event and get the list of file selected.
List<multiSearchSelect> multiSearchSelect = new List<multiSearchSelect>();
private void FilesFoundList_VirtualItemsSelectionRangeChanged(object sender, ListViewVirtualItemsSelectionRangeChangedEventArgs e)
{
if (FilesFoundList.VirtualMode == true)
{
multiSearchSelect.Clear();
ListView.SelectedIndexCollection col = FilesFoundList.SelectedIndices;
if (col.Count > 1)
{
foreach (int item in col)
{
multiSearchSelect.Add(new multiSearchSelect
{
fileName = FilesFoundList.Items[item].SubItems[1].Text,
filePath = FilesFoundList.Items[item].SubItems[2].Text
});
}
}
}
}
class multiSearchSelect
{
public string fileName { set; get; }
public string filePath { set; get; }
}
Related
Goal:Is to display Project name, formed by joining list box selected items with user entered text in the text box and display it as a label.
Description: I am creating a windows for App, which has two listboxes displaying Firstname-lbA & Lastname- lbB along with a textbox for the user to enter packet name.
For example: If I select an item(first name)from the listbox A i.e. "XXX", select an item(last name)from the listbox B i.e. "YYY" and enter text in the Textbox i.e. "PKT-100" & click create button I would want to display the Project name as XXX-YYY-PKT-100.
checking conditions:
If no Item in lbA is selected then display:YYY-PKT-100.
If no Item in Lb B is seleected then display :XXX-PKT-100.
If no Text is entered the display: XXX-YYY.
No spaces/double dashes are allowed.
I'd really appreciate if someone could help me with your suggestions.
Thanks!!
Code:
FirstNamespace Project
{
public partial class ProjectTool : Form
{
public List<FirstName> ltfirstname { get; set; }
public List<LastName> ltlastname { get; set; }
public FirstName SelectedFirstname => (FirstName)lbGetFirstName.SelectedItem
public LastName SelectedLastname => (LastName)lbGetLastName.SelectedItem;
public projecTool()
{
InitializeComponent();
ltfirstname = GetFirstNames();
lbGetFirstName.DataSource = ltfirstname;
ltlastname = GetLastNames();
lbGetLastName.DataSource = ltlastname;
}
public List<FirstName> GetFirstNames()
{
List<FirstName> fnames = new List<FirstName>();
using (StreamReader sr = new StreamReader("D:\\FirstNames.csv"))
{
string line;
try
{
while ((line = sr.ReadLine()) != null)
{
string[] columns = line.Replace("\"","").Split(',');
if (columns.Length >= 1)
{
var name = new FirstName();
name.FirstName = columns[0];
fnames.Add(name);
}
}
}
catch (Exception ex) { }
return fnames;
}
}
public List<LastName> GetlastNames()
{
List<LastName> lnames = new List<LastName>();
using (StreamReader sr = new StreamReader("D:\\LastNames.csv"))
{
string line;
try
{
while ((line = sr.ReadLine()) != null)
{
string[] columns = line.Replace("\"","").Split(',');
if (columns.Length >= 1)
{
var lname = new LastName();
lname.LastName = columns[0];
lnames.Add(lname);
}
}
}
catch (Exception ex) { }
return lnames;
}
}
public void CreateprojectName()
{
// Create project name as Firstname-Lastname-Packetname
//if project name already exists then check for correctness/update.
// Check -> if there are double dashes/spaces in the Project name
}
private void lbGetFirstName_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void lbGetlastName_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void txtPacketName_TextChanged(object sender, EventArgs e)
{
}
private void create_projectname_button1_Click(object sender, EventArgs e)
{
}
}
}
Its quite simple for listBox use SelectedItem & for textBox use Text property.
private void create_projectname_button1_Click(object sender, EventArgs e)
{
if (lbGetFirstName.SelectedItems.Count==0)
{
label1.Text = "YYY-PKT-100";
}
if (lbGetlastName.SelectedItems.Count==0)
{
label1.Text = "XXX-PKT-100";
}
if (string.IsNullOrWhiteSpace(textBox1.Text))
{
label1.Text = "XXX-YYY";
}
else
{
label1.Text = lbGetFirstName.SelectedItem + "-" + listBox2.SelectedItem + "-" + lbGetlastName.Text;
}
}
I'm sorry if my title is bad, its 1:30am and I'm all out of coffee. I've tried a few solutions suggested on similar questions but I can't figure it out as my case is a little different.
I'm trying to use a separate form to select parameters for the method I use to format data which is passed to a DataGridView in the original form, however its not populating the DataGridView. I have set the new form to be a dialog, it receives the original form reference when its called, on the form there is a DateTimePicker and a button, when the button is clicked it calls a method that gets the datetime value, then it calls a method on the original form with the datetime parameters being passed to it and closes the dialog. The method on the original form runs with the parameters that where passed to get the data for the DataGridView and then calls the datasource method passing the bindinglist to it.
This method of filling the DataGridView using a dialog is my best interpretation of how its been explained in similar questions on this site but its not populating my DataGridView. Any help would be greatly appreciated.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
SearchDialog search = new SearchDialog(this);
search.Show();
}
)button2 is a cancel button(
public partial class SearchDialog : Form
{
static DirectoryInfo DexFolder = new DirectoryInfo(Properties.Settings.Default.DexFolderPath);
static DirectoryInfo ExcelFile = new DirectoryInfo(Properties.Settings.Default.ExcelFilePath);
public SearchDialog(Main form)
{
InitializeComponent();
fromDateSelector.Checked = false;
toDateSelector.Checked = false;
MainForm = form;
}
public Main MainForm {get; set;}
private void button2_Click(object sender, EventArgs e)
{
Close();
}
private void button1_Click(object sender, EventArgs e)
{
SearchParameters();
Close();
}
private void SearchParameters()
{
DateTime allTime = DateTime.Now.AddYears(-150);
DateTime current = DateTime.Now;
if (fromDateSelector.Checked == true)
{
allTime = fromDateSelector.Value;
}
if (toDateSelector.Checked == true)
{
current = toDateSelector.Value;
}
MainForm.GetFiles(DexFolder, current, allTime);
}
}
(back on Main form)
public void GetFiles(DirectoryInfo FilePath, DateTime from, DateTime to)
{
List<string> DexFileNames = new List<string>();
List<string> DexData = new List<string>();
IList<FileManagerView> fileManagerData = new BindingList<FileManagerView>();
string[] ExcelData = File.ReadAllLines(ExcelFile.ToString());
foreach (FileInfo fileInfo in FilePath.GetFiles("*.dex"))
{
DexFileNames.Add(fileInfo.Name);
}
foreach (string DexFileName in DexFileNames)
{
DateTime dexDate = File.GetCreationTime(FilePath + DexFileName);
string[] NameData = DexFileName.Split('_', '-', '.');
if (NameData.Length > 2)
{
dexDate = DateTime.ParseExact(NameData[1] + NameData[2], "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
}
string DexPHYSID = NameData[0];
string machineNumber = "";
string machineLocation = "";
string telemetryDevice = "";
string routeNumber = "";
string machinePHYSID = "";
string driverName = "";
foreach (string line in ExcelData)
{
string[] lineData = line.Split(',');
if (DexPHYSID == lineData[14].Trim('"'))
{
machinePHYSID = lineData[14].Trim('"');
machineNumber = lineData[0].Trim('"');
machineLocation = lineData[2].Trim('"');
string RouteNumberFull = lineData[17].Trim('"');
string[] DriverName = lineData[18].Trim('"').Split('(');
telemetryDevice = lineData[8].Trim('"');
string[] RouteNumberData = RouteNumberFull.Split(' ');
driverName = DriverName[0];
try
{
routeNumber = RouteNumberData[1] + " " + RouteNumberData[2];
}
catch
{
}
}
}
if (DexPHYSID == machinePHYSID)
{
FileManagerView fileManagerView = new FileManagerView();
if (dexDate.ToString("dd-MM-yy") == from.ToString("dd-MM-yy") && dexDate.ToString("dd-MM-yy") == to.ToString("dd-MM-yy"))
{
fileManagerView.machineNumber = machineNumber;
fileManagerView.machineLocation = machineLocation;
fileManagerView.telemetryDevice = telemetryDevice;
fileManagerView.physid = DexPHYSID;
fileManagerView.routeNumber = routeNumber;
fileManagerView.date = dexDate;
fileManagerView.driver = driverName;
fileManagerData.Add(fileManagerView);
}
}
}
FileManagerPopulate(fileManagerData);
}
public class FileManagerView
{
public string machineNumber { get; set; }
public string machineLocation { get; set; }
public string telemetryDevice { get; set; }
public string physid { get; set; }
public string routeNumber { get; set; }
public string driver { get; set; }
public DateTime date { get; set; }
}
public void FileManagerPopulate(IList<FileManagerView> data)
{
dataGridView1.DataSource = data;
}
So the problem was the use of == operands instead of > and < when the GetFiles() method was checking if the file date was within the selected range.
I'm going to leave this here as it may help someone else looking for answers.
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);
I want to add two lists to the box. It doesn't have a problem with adding items to the listbox, but a problem occurs when I try to click on one of the items and show a related form with details filled in to allow users to make amendments. Obviously the form didn't show, but instead an error occurs, no matter if I was try to open the form "delivery" or "pickup". The problem still occurs on one line
Error:
An unhandled exception of type 'System.InvalidCastException' occurred
in coursework2.exe
Additional information: Unable to cast object of type 'System.String'
to type 'coursework2.Pickup'.
namespace coursework2
{
public partial class MainForm : Form
{
private DeliveryForm deliveryform = new DeliveryForm();
private List<Visit> requests = new List<Visit>();
private Visit theVisit = new Visit();
private PickupForm pickupform = new PickupForm();
public void requestVisit(Visit newVisit)
{
requests.Add(newVisit);
}
public MainForm()
{
InitializeComponent();
}
private void btnNpickup_Click(object sender, EventArgs e)
{
pickupform.pickup = new Pickup();
pickupform.ShowDialog();
if (pickupform.pickup != null)
{
Pickup newPu = pickupform.pickup;
theVisit.addPick(newPu);
List<String> listOfPic = theVisit.listofPicks();
listboxVisits.Items.AddRange(listOfPic.ToArray());
}
updateList();
//this will upload details from pickup form to the list
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void MainForm_Load(object sender, EventArgs e)
{
}
private void btnNdelivery_Click(object sender, EventArgs e)
{
deliveryform.delivery = new Delivery();
deliveryform.ShowDialog();
if (deliveryform.delivery != null)
{
Delivery newDe = deliveryform.delivery;
theVisit.addDeliver(newDe);
List<String> listOfDel = theVisit.listofDeliver();
listboxVisits.Items.AddRange(listOfDel.ToArray());
}
updateList();
//this will upload detail of the delivery to the list
}
private void btnVall_Click(object sender, EventArgs e)
{
}
private void updateList()
{
listboxVisits.Items.Clear();
List<String> listofVis = theVisit.LisitVisits();
listboxVisits.Items.AddRange(listofVis.ToArray());
}
private void listboxVisits_SelectedIndexChanged(object sender, EventArgs e)
{
listboxVisits.FormattingEnabled = false;
int index = listboxVisits.SelectedIndex;
if (listboxVisits.SelectedItems.Count>0)
{
object object1 = listboxVisits.SelectedItems[0];
if (object1 is Delivery)
{
Delivery deliver = (Delivery)object1;
deliveryform.delivery = deliver;
deliveryform.ShowDialog();
}
else
{
Pickup pick = (Pickup)object1;// this is where error occur
pickupform.pickup = pick;
pickupform.ShowDialog();
}
}
this is the pickup class
public class Pickup
{
private string pickupname;
private string pickupaddress;
private Visit collects;
private Delivery sends;
private DateTime pdatetime;
private string dname;
private string daddress;
private DateTime dtime;
public string PickupName
{
get { return pickupname; }
set { pickupname = value; }
}
public string PickupAddress
{
get { return pickupaddress; }
set { pickupaddress = value; }
}
public string Dname
{
get { return dname; }
set { dname = value; }
}
public string Daddress
{
get { return daddress; }
set {daddress = value; }
}
public DateTime Pdatetime
{
get { return pdatetime; }
set { pdatetime = value; }
}
public DateTime Dtime
{
get { return dtime; }
set { dtime = value; }
}
public override string ToString()
{
return pickupname + " " + pickupaddress + " " + pdatetime.ToString()+" "+dname+" "+daddress+" "+dtime.ToString()+" Pickup ";
}
}
this is the visit class
public class Visit : Customer
{
private Customer requester;
private DateTime datetime;
private Delivery reciever;
private Pickup collect;
public DateTime DateTime
{
get { return datetime; }
set { datetime = value; }
}
private List<Pickup> picks = new List<Pickup>();
private List<Visit> visits = new List<Visit>();
private List<Delivery> deliver = new List<Delivery>();
public void addDeliver(Delivery de)
{
//adding new Delivery ToString the visit
deliver.Add(de);
}
public List<String> listofDeliver()
{
List<string> listofDeliver = new List<string>();
foreach (Delivery de in deliver)
{
String deAsString = de.ToString();
listofDeliver.Add(deAsString);
}
return listofDeliver;
}
public Delivery getDeliver(int index)
{
int count = 0;
foreach (Delivery de in deliver)
{
if (index == count)
return de;
count++;
}
return null;
}
public void addPick(Pickup pu)
{
picks.Add(pu);
}
public List<String> listofPicks()
{
List<string> listofPicks = new List<string>();
foreach (Pickup pu in picks)
{
String puAsString = pu.ToString();
listofPicks.Add(puAsString);
}
return listofPicks;
}
public Pickup getPicks(int index)
{
int count = 0;
foreach (Pickup pu in picks)
{
if (index == count)
return pu;
count++;
}
return null;
}
public List<String> LisitVisits()
{
List<String> visits = new List<string>();
visits.AddRange(listofDeliver());
visits.AddRange(listofPicks());
return visits;
}
public Visit getVisits(int index)
{
int count = 0;
foreach (Visit vis in visits)
{
if (index == count)
return vis;
count++;
}
return null;
}
public string VisitDetails()
{
return collect.PickupName + " " + collect.PickupAddress + " Pickup " + reciever.DeliveryName + " " + reciever.DeliveryAddress + " Delivery";
}
}
I've a problem. In my code I'm looking for all xml files in one directory. Finally it works but I don't know how to read them. A single one is loaded with the string xmlFile. I think I need to replace or edit that in this way that my code now that xmlFile is not only one file, but all files who are found in the directory.
What should I be doing?
namespace WindowsFormsApplication11
{
public partial class Form1 : Form
{
private const string xmlFile = "C:\Games\games.xml"; // single xml file works
public Form1()
{
this.InitializeComponent();
this.InitializeListView();
this.LoadDataFromXml();
listView.Items.AddRange(Directory.GetFiles("C:\Games\", "*.xml")
.Select(f => new ListViewItem(f))
.ToArray());
}
private void LoadDataFromXml()
{
if (File.Exists(xmlFile))
{
XDocument document = XDocument.Load(xmlFile);
if (document.Root != null)
{
foreach (XElement gameElement in document.Root.Elements("game"))
{
string gamename = gameElement.Element("gamename").Value;
string launchpath = gameElement.Element("launchpath").Value;
string uninstallpath = gameElement.Element("uninstallpath").Value;
string publisher = gameElement.Element("publisher").Value;
// check if gameElement.Element(ELEMENTNAME) is not null
Game game = new Game(gamename, launchpath, uninstallpath, publisher);
AddGameToListView(game);
}
}
}
}
private void AddGameToListView(Game game)
{
ListViewItem item = CreateGameListViewItem(game);
this.listView.Items.Add(item);
}
private ListViewItem CreateGameListViewItem(Game game)
{
ListViewItem item = new ListViewItem(game.Gamename);
item.SubItems.Add(game.Launchpath);
item.SubItems.Add(game.Uninstallpath);
item.SubItems.Add(game.Publisher);
item.Tag = game;
return item;
}
private void InitializeListView()
{
this.listView.View = View.Details;
this.listView.GridLines = true;
this.listView.MultiSelect = false;
this.listView.FullRowSelect = true;
this.listView.Columns.AddRange(new[]
{
new ColumnHeader{Text = "Gamename", Width = 200},
new ColumnHeader{Text = "Launchpath"},
new ColumnHeader{Text = "Uninstallpath"},
new ColumnHeader{Text = "Publisher"}
});
this.listView.MouseDoubleClick += ListViewOnMouseDoubleClick;
}
private void ListViewOnMouseDoubleClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && this.listView.SelectedItems.Count > 0)
{
Game game = (Game)((this.listView.SelectedItems[0].Tag);
try
{
Process.Start(game.Launchpath);
}
catch (Exception ex)
{
MessageBox.Show("Can not start game.\nDetails:\n" + ex.Message, "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}
internal class Game
{
public Game()
{
}
public Game(string gamename, string launchpath, string uninstallpath, string publisher)
{
this.Gamename = gamename;
this.Launchpath = launchpath;
this.Uninstallpath = uninstallpath;
this.Publisher = publisher;
}
public string Gamename { get; set; }
public string Launchpath { get; set; }
public string Uninstallpath { get; set; }
public string Publisher { get; set; }
}
}
UPDATE:
This is my current code. how can i send f to LoadDataFromXml ?
public Form1()
{
this.InitializeComponent();
this.InitializeListView();
this.Height = Screen.PrimaryScreen.WorkingArea.Height;
var files = Directory.GetFiles(#"C:\Games\", "*.xml").Select(f => new ListViewItem(f)).ToArray(); listView.Items.AddRange(files);
foreach (var f in files)
{
this.LoadDataFromXml(f);
}
}
private void LoadDataFromXml(//What Do I need to enter here?)
{
foreach (XElement gameElement in f.Root.Elements("game"))
{
string gamename = gameElement.Element("gamename").Value;
string launchpath = gameElement.Element("launchpath").Value;
string portablesave = gameElement.Element("portablesave").Value;
string publisher = gameElement.Element("publisher").Value;
string gameid = gameElement.Element("gameID").Value;
string update = gameElement.Element("update").Value;
// check if gameElement.Element(ELEMENTNAME) is not null
Game game = new Game(gamename, launchpath, portablesave, publisher, gameid, update);
AddGameToListView(game);
}
}
Simple use Directory functions to get all your XML files, and loop through them, by calling LoadDataFromXml for each file. Note: You will need to refactor your code a little bit.
You need to modify your LoadDataFromXml to take file as a parameter. And change your Form1 constructor to something like this
public Form1()
{
this.InitializeComponent();
this.InitializeListView();
var files = Directory.GetFiles("C:\Games\", "*.xml")
.Select(f => new ListViewItem(f))
.ToArray();
listView.Items.AddRange(files);
foreach(var f in files)
{
this.LoadDataFromXml(f);
}
}