May I know is there a shorter way to add items to the comboBox? Currently I am only adding 20 items which already seems very long, what if I have a 100 items to add into the comboBox?
My code:
private void loadSharePricesComboBox()
{
comboComSymbol.Items.Add("BARC");
comboComSymbol.Items.Add("DEB");
comboComSymbol.Items.Add("DOM");
comboComSymbol.Items.Add("EZJ");
comboComSymbol.Items.Add("GFS");
comboComSymbol.Items.Add("IHG");
comboComSymbol.Items.Add("JD.");
comboComSymbol.Items.Add("LAD");
comboComSymbol.Items.Add("LLOY");
comboComSymbol.Items.Add("MRW");
comboComSymbol.Items.Add("NXT");
comboComSymbol.Items.Add("OCDO");
comboComSymbol.Items.Add("RBS");
comboComSymbol.Items.Add("SMWH");
comboComSymbol.Items.Add("SPD");
comboComSymbol.Items.Add("STAN");
comboComSymbol.Items.Add("SYR");
comboComSymbol.Items.Add("TALK");
comboComSymbol.Items.Add("TSCO");
comboComSymbol.Items.Add("WMH");
comboComSymbol.SelectedIndex = -1;
}
Your help is much appreciated! Thank you. :)
Addition code (for the question i asked Simon Whitehead):
private void btnDownloadXML_Click(object sender, EventArgs e)
{
using (WebClient client = new WebClient())
{
client.DownloadFile("http://www.lse.co.uk/chat/" + comboDownloadXML.SelectedItem,
#"..\..\sharePriceXML\" + comboDownloadXML.SelectedItem + ".xml");
}
MessageBox.Show("Download Completed! File has been placed in the folder sharePriceXML!");
}
Have you tried the AddRange() method?
I haven't tested:
private void loadSharePricesComboBox()
{
comboComSymbol.Items.AddRange(new string[]{"BARC", "DEB", ... etc});
comboComSymbol.SelectedIndex = -1;
}
The MSDN on .AddRange might give you a better idea.
foreach(var item in "BARC,DEB,DOM,...".Split(',')) comboComSybol.Items.Add(item);
or
var items = new [] { "BARC", "DEV", "DOM" };
foreach(var item in items) comboComSymbol.Items.Add(item);
or you can save even more code and use AddRange on the above 2 methods.
var items = new [] { "BARC", "DEV", "DOM" };
comboComSymbol.Items.AddRange(items);
If you are starting a new project though, have a look at WPF instead of winforms.
Use ListBox.ObjectCollection.AddRangeYou can use it like this:comboComSymbol.Items.AddRange(new string[] {"ABC", "DEF", "GHI"});
To save on code size.. why not list them in a file?
void loadSharePricesComboBox(string fileName) {
using (StreamReader sr = new StreamReader(fileName)) {
while (!sr.EndOfStream) {
comboComSymbol.Items.Add(sr.ReadLine());
}
}
}
EDIT: In response to your comment.. I would just load the files, without extensions.. that would be much easier:
void loadSharePricesComboBox(string path) {
foreach (string file in Directory.GetFiles(path, "*.xml")) {
comboComSymbol.Items.Add(Path.GetFileNameWithoutExtension(file));
}
}
Pass in the path you want to load the XML file names from, perhaps like this:
loadSharePricesComboBox(#"..\..\sharePriceXML\");
This will load all the XML file names, without their extensions, giving you the list you require.
use generic List<T> to databind.
class Symbols
{
public string Name{get;set;}
}
var Symb= new List<Symbols> { new Symbols() { Name = "Abc"}, new Person() { Name = "BC" }};
comboBox1.DisplayMember = "Name";
comboBox1.DataSource = Symb;
comboBox1.DataBindings.Add("SelectedItem", Symb, "Name");
this code :
string[] str = {
"BARC","DEB","DOM","EZJ","GFS","IHG","JD.","LAD","LLOY","MRW",
"NXT","OCDO","RBS","SMWH","SPD","STAN","SYR","TALK","TSCO","WMH"
};
loadSharePricesComboBox(str);
your method :
private void loadSharePricesComboBox(string[] strArr)
{
comboComSymbol.Items.AddRange(strArr);
comboComSymbol.SelectedIndex = -1;
}
Related
Is it possible to get only list of Excel filenames (like : 2021070701.CSV) in a folder ?
I'm getting the full path of the .csv excel when I use this "Directory.GetFiles" but I want to filter only excel filename with extension (like : 2021070701.CSV)
I used "FileInfo fi = new FileInfo();" but I didn't get the proper solution.
public static void getExcelFileName()
{
string[] filename = Directory.GetFiles(#"C:\Users\Ashok
Kumar\OneDrive\Desktop\Ashok\MarketPrice\NSE\Futures\Live", "*.csv");
foreach (var item in filename)
{
Console.WriteLine(item);
}
}
This is the path I'm getting
Help me out form this I'm new to coding.
You can use the GetFileNameWithoutExtension() method from the Path class to get the names of your files.
public static void getExcelFileName()
{
string[] filename = Directory.GetFiles(#"C:\Users\Ashok
Kumar\OneDrive\Desktop\Ashok\MarketPrice\NSE\Futures\Live", "*.csv");
foreach (var item in filename)
{
Console.WriteLine(Path.GetFileNameWithoutExtension(item));
}
}
Sure, you can call Path.GetFileName(string) which returns exactly what you're asking for!
public static void getExcelFileName()
{
string[] filesPaths = Directory.GetFiles(#"C:\Users\Ashok Kumar\OneDrive\Desktop\Ashok\MarketPrice\NSE\Futures\Live",
"*.csv");
foreach (var filePath in filesPaths)
{
Console.WriteLine(Path.GetFileName(filePath));
}
}
How can I ban a variable from a list without removing it from that list by adding the variable to a list of "banned" variable?
I wish to be able to type in a string. That string is compared to the file names in a folder. If there is a match, the file is read. If I type this same string again, the file should not be read again. There for I want to have a list of "banned" string that is checked whilst typing to avoid the file to be read again.
I have tried a few ways but not getting there. Below is an example of my last attempt.
What would be the best way?
public class test
{
string scl= "test3";
List <string> lsf,lso;
void Start ()
{
lsf=//file names
new List<string>();
lso=//files open
new List<string>();
lsf.Add("test0");
lsf.Add("test1");
lsf.Add("test2");
lsf.Add("test3");
lsf.Add("test4");
lso.Add("idhtk49fngo");//random string
}
void Update ()
{
if
(
Input.GetKeyDown("a")
)
{
for
(
int i=0;
i<lsf.Count;
i++
)
{
if(lsf[i]==scl)
{
Debug.Log
(i+" is read");
for
(
int j=0;
j<lso.Count;
j++
)
{
//how can i avoid reading
//lsf[3] here the second time
//"a" is pressed (by having "test3"
//added to a "ban" list (lso) )
if(scl!=lso[j])
{
lso.Add(lsf[i]);
}
}
}
}
}
}
Michael’s answer is the way to go here but it can be improved using the more appropriate collection available to keep track of opened files; if you want uniqueness use a set, not a list:
HashSet<string> openedFiles = new HashSet<string>();
public static bool TryFirstRead(
string path,
out string result)
{
if (openedFiles.Add(path))
{
result = File.ReadAllText(path);
return true;
}
result = null;
return false;
}
Also, I’d avoid throwing vexing exceptions. Give the consumer a friendly way to know if the file was read or not, don’t make them end up having to use exceptions as a flow control mechanism.
I didn't understand although if you want to replace a value from another list.
You can use the list index to create a new list with the values which you removed.
String list1 = {"hi", "hello", "World"};
String list2 = {"bye", "goodbye", "World"};
List1[1] = list2[1];
I would suggest such way:
public static List<string> openedFiles = new List<string>();
public static string ReadFileAndAddToOpenedList(string path)
{
if (openedFiles.Contains(path))
throw new Exception("File already opened");
// Instead of throwing exception you could for example just log this or do something else, like:
// Consolle.WriteLine("File already opened");
else
{
openedFiles.Add(path);
return File.ReadAllText(path);
}
}
The idea is - on every file read, add file to list, so you can check every time you try read file, if it was already read (or opened). If it is, throw exception (or do something else). Else read a file.
You could instead of making it a string list use your own class
public class MyFile
{
public string Name;
public bool isOpen;
public MyFile(string name)
{
Name = name;
isOpen = false;
}
}
List<MyFile> lsf = new List<MyFile>()
{
new MyFile("test0"),
new MyFile("test1"),
new MyFile("test2"),
new MyFile("test3"),
new MyFile("test4")
};
Than when you read the file set isOpen to true
MyFile[someIndex].isOpen = true;
and later you can check this
// E.g. skip in a loop
if(MyFile[someIndex]) continue;
You could than also use Linq in order to get a list of only unread files:
var unreadFiles = lsf.Select(f => f.Name).Where(file => !file.isOpen);
I have a combobox which gets the list of items from the name of files I put together in one directory, the purpose for this is to make it dynamic - I'm very new to c# and it didn't occur to me a different way. - Here's the code for that bit:
string[] files = Directory.GetFiles(templatePath);
foreach (string file in files)
cbTemplates.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file));
Basically, that works just fine, it populates my combobox with the names of the files I have in that path, the problem is that I need to open the file that's selected in the combobox and read its contents and place them in labels, I was thinking maybe StreamReader would help me here but I have NO clue on how to implement it, I've searched the internet but it looks like no one had the same idea before me. Can someone please point me in the right direction? A link to something similar or a guide of the objects I need to use would be great, thanks!
what you should do is store the names of the files in a single separate file (csv or xml). then use this file to both load the combobox and as an indexer.
for example lets say you have files a.txt, b.txt, and c.txt. you should (as you already are) read the file names programmatically THEN write them to a new file in whichever format you want, including a unique index scheme (numbers work fine).
your csv might look like this:
1, a.txt,
2, b.txt,
3, c.txt,
from here you can parse the newly created csv to your liking. Use it to populate your combobox, index being its value and filename its text. Then you can read your combobox selectedvalue, get the proper filename from the csv index, and finally open the file.
It may be longwinded but it'll work. You could also just use a multidimensional array, but this is more fun from an educational stand point, and it will help you with read/write operations.
It is not so easy to understand your problem. Do you want just to display filename w/o extension in your combobox? I hope this code will be usefull to you.
internal class FileDetail
{
public string Display { get; set; }
public string FullName { get; set; }
}
public partial class Example: Form // This is just widows form. InitializeComponent is implemented in separate file.
{
public Example()
{
InitializeComponent();
filesList.SelectionChangeCommitted += filesListSelectionChanged;
filesList.Click += filesListClick;
filesList.DisplayMember = "Display";
}
private void filesListClick(object sender, EventArgs e)
{
var dir = new DirectoryInfo(_baseDirectory);
filesList.Items.AddRange(
(from fi in dir.GetFiles()
select new FileDetail
{
Display = Path.GetFileNameWithoutExtension(fi.Name),
FullName = fi.FullName
}).ToArray()
);
}
private void filesListSelectionChanged(object sender, EventArgs e)
{
var text = File.ReadAllText(
(filesList.SelectedItem as FileDetail).FullName
);
fileContent.Text = text;
}
private static readonly string _baseDirectory = #"C:/Windows/System32/";
}
Thanks for all your help folks but I figured out how to get around my issue, I'll post the code for future incidents. pd. Sorry it took me this long to reply, I was on vacation
string[] fname = Directory.GetFiles(templatePath); // Gets all the file names from the path assigned to templatePath and assigns it to the string array fname
// Begin sorting through the file names assigned to the string array fname
foreach (string file in fname)
{
// Remove the extension from the file names and compare the list with the dropdown selected item
if (System.IO.Path.GetFileNameWithoutExtension(file) != cbTemplates.SelectedItem.ToString())
{
// StreamReader gets the contents from the found file and assigns them to the labels
using (var obj = new StreamReader(File.OpenRead(file)))
{
lbl1.Content = obj.ReadLine();
lbl2.Content = obj.ReadLine();
lbl3.Content = obj.ReadLine();
lbl4.Content = obj.ReadLine();
lbl5.Content = obj.ReadLine();
lbl6.Content = obj.ReadLine();
lbl7.Content = obj.ReadLine();
lbl8.Content = obj.ReadLine();
lbl9.Content = obj.ReadLine();
lbl10.Content = obj.ReadLine();
obj.Dispose();
}
}
}
Thanks all for the suggestion made for my earlier query regarding to the getlist and copy.
I have only one issue here
String realname= "test" //am getting this value from Db,so is this anyway i can use like that rather than
string realname="test"//i know i can do like string realname=""+Dbvalue+"";
Am just wondering why it doesn't return anyvalue if don't use "*" ?
class Program
{
static void Main(string[] args)
{
var getfiles = new fileshare.Program();
string realname = "*test*";
foreach (var file in getfiles.GetFileList(realname))
{getfiles.copytolocal(file.FullName); }
}
private FileInfo[] GetFileList(string pattern)
{
var di = new DirectoryInfo(#"\\testserv01\dev");
return di.GetFiles(pattern);
}
private void copytolocal(string filename)
{
string nameonly = Path.GetFileName(filename);
File.Copy(filename,Path.Combine(#"c:\",nameonly));
}
}
Thanks in Advance.
I know this is a bit glib but really you need to start looking at the documentation of the functionality you are using: http://msdn.microsoft.com/en-us/library/8he88b63.aspx
that said the reason is that * is a wildcard - if you use "test" then you will only retrieve exact matches for "test".
the link above has some more examples.
update
I'm writing a silverlight application and I have the following Class "Home", in this class a read a .xml file a write these to a ListBox. In a other class Overview I will show the same .xml file. I know it is stupid to write the same code as in the class "Home".
The problem is, how to reach these data.
My question is how can I reuse the method LoadXMLFile() from another class?
The code.
// Read the .xml file in the class "Home"
public void LoadXMLFile()
{
WebClient xmlClient = new WebClient();
xmlClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(XMLFileLoaded);
xmlClient.DownloadStringAsync(new Uri("codeFragments.xml", UriKind.RelativeOrAbsolute));
}
private void XMLFileLoaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
string xmlData = e.Result;
XDocument xDoc = XDocument.Parse(xmlData);
var tagsXml = from c in xDoc.Descendants("Tag") select c.Attribute("name");
List<Tag> lsTags = new List<Tag>();
foreach (string tagName in tagsXml)
{
Tag oTag = new Tag();
oTag.name = tagName;
var tags = from d in xDoc.Descendants("Tag")
where d.Attribute("name").Value == tagName
select d.Elements("oFragments");
var tagXml = tags.ToArray()[0];
foreach (var tag in tagXml)
{
CodeFragments oFragments = new CodeFragments();
oFragments.tagURL = tag.Attribute("tagURL").Value;
//Tags.tags.Add(oFragments);
oTag.lsTags.Add(oFragments);
}
lsTags.Add(oTag);
}
//List<string> test = new List<string> { "a","b","c" };
lsBox.ItemsSource = lsTags;
}
}
Create a class to read the XML file, make references to this from your other classes in order to use it. Say you call it XmlFileLoader, you would use it like this in the other classes:
var xfl = new XmlFileLoader();
var data = xfl.LoadXMLFile();
If I were you, I would make the LoadXMLFile function take a Uri parameter to make it more reusable:
var data = xfl.LoadXMLFile(uriToDownload);
You could create a class whose single responsibility is loading XML and returning it, leaving the class that calls your LoadXmlFile method to determine how to handle the resulting XML.