I have a textbox that I want to use to autosearch my text file and display the results in the listbox. the listbox already contains the first item of each line in the text file, so I basically want to search using only the first item of every line in the text file.
The code I currently have does nothing.
private void custsearchbox_TextChanged(object sender, EventArgs e)
{
string[] autosource = File.ReadAllLines(#"data\Suppliers.txt");
for (int g = 0; g < autosource.Length; g++)
{
custsearchbox.AutoCompleteCustomSource.Add(autosource[g]);
}
custsearchbox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
}
I want to type the first item in my text box and search my listbox, as I enter my text I want the list to filter out the items that does not match. Please help me achieve this.
I tried this:
private void supsearchtxt_TextChanged(object sender, EventArgs e)
{
listsup.Items.Clear();
Supfile = System.AppDomain.CurrentDomain.BaseDirectory + "data\\Suppliers.txt";
List<string> proName = new List<string>();
using (StreamReader rdr = new StreamReader(Supfile))
{
string line;
while ((line = rdr.ReadLine()) != null)
{
if (line.Contains(supsearchtxt.Text))
{
string[] val = line.Split(',');
listsup.Items.Add(val[0]);
}
}
}
}
and it works great.
Related
So I have a combo box that contains a list of trainees that is imported from a textfile (each trainee occupies a line in the textfile) and I have 3 buttons, add (adds a new trainee to the file and combobox), delete(Supposed to delete the specific line in the file containing the combobox selected item) and a modify button (supposed to overwrite a new trainee in the file at the same line that contains the combobox selected item), my add button works fine, idk how to modify or delete lines in a file.
I have no idea how to work this around as I'm new to working with files
here's my code
private void form1_Load(object sender, EventArgs e)
{
FileStream fs = new FileStream("trainee.txt", FileMode.Open);
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(fs))
{
string line;
while ((line = r.ReadLine()) != null)
{
comboBox1.Items.Add(line);
}
}
fs.Close();
}
private void deleteButton_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem == null)
{
MessageBox.Show("Choose a trainee to delete.", "Error !");
}
else
{
string selection = comboBox1.SelectedItem.ToString();
FileStream fs = new FileStream("stagiaire.txt", FileMode.Open);
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(fs))
{
string line;
while ((line = r.ReadLine()) == selection)
{
}
}
fs.Close();
private void button2_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem == null)
{
MessageBox.Show("Choose a trainee to modify.", "Error !");
}
else
{
string selection = comboBox1.SelectedItem.ToString();
FileStream fs = new FileStream("trainee.txt", FileMode.Open);
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(fs))
{
string line;
if ((line = r.ReadLine()) == selection)
{
Trainee stg = new Trainee();
stg.name = textBox1.Text;
stg.nickname = textBox2.Text;
stg.training_days = int.Parse(textBox3.Text);
addtrainee(stg);
comboBox1.Items.Add(stg);
}
}
fs.Close();
}
You may be working too hard, the List you have is working for you here. Whenever you need to output it, just write the whole list. When you need to manipulate the entries in it (elements), use the collection methods like Find, Contains, Add, Remove, others see (https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=netframework-4.7.2#methods)
You can shortcut you file access too, use the framework:
var fileLines = File.ReadLines("c:/temp/yourfile.txt");
No using and StreamReader/Writer needed, depending on your environment too I guess.
So you have your input as string and List<string> so you could do if (lines.Contains(testString)) for example.
Can provide more sample code if it helps.
I am trying to come up with a solution where I can search items inside a combo box that contain certain word/phrase. I tried using the AutoComplete text box functionality, but that only searches for the first word which is no good to me.
I have followed the example provided at https://social.msdn.microsoft.com/Forums/vstudio/en-US/4c229a73-cdad-4fa3-95db-97f9ff7810c1/autocomplete-match-on-contains-not-startswith?forum=netfxbcl
I have initiated 2 lists
public List<string> listOnit = new List<string>();
public List<string> listNew = new List<string>();
I then load the data into a comboBox
if (rdr.HasRows == true)
{
// var source = new List<string>();
while (rdr.Read())
{
// myCollectionSales.Add(rdr[0].ToString());
listOnit.Add(rdr[0].ToString());
}
rdr.Close();
//textBox1.AutoCompleteCustomSource = myCollectionSales;
comboBox1.Items.AddRange(listOnit.ToArray());
}
and have a TextUpdate event handler to filter the list when text has changed
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
comboBox1.Items.Clear();
listNew.Clear();
foreach (var item in listOnit)
{
if (item.Contains(this.comboBox1.Text))
{
listNew.Add(item);
}
}
comboBox1.Items.AddRange(listNew.ToArray());
comboBox1.SelectionStart = this.comboBox1.Text.Length;
Cursor = Cursors.Default;
comboBox1.DroppedDown = true;
}
I am coming across a problem where the search results don't return what I expect. For example, I search for the string "Bud" and I only get the following results
http://prntscr.com/ppkatd
While in the database, there is also Budweiser 33cl and Keg Budweiser (http://prntscr.com/ppkbu4), for example, which is fetched on the first list.
Should I be using a different method, rather than "Contains"?
Perhaps you are using different cases?
Try with .ToLower():
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
comboBox1.Items.Clear();
listNew.Clear();
foreach (var item in listOnit)
{
if (item.ToLower().Contains(this.comboBox1.Text.ToLower()))
{
listNew.Add(item);
}
}
comboBox1.Items.AddRange(listNew.ToArray());
comboBox1.SelectionStart = this.comboBox1.Text.Length;
Cursor = Cursors.Default;
comboBox1.DroppedDown = true;
}
I am new to using the DataGridView component, I've used it once before and have managed to complete this exact task but I forgot how I achieved it.
Basically I would like to read the values from a text file which is formatted like so:
line 1,
line 2,
line 3
Here is the code I currently have:
List<string> tokens = new List<string>();
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
string[] lines = (string[])e.Data.GetData(DataFormats.FileDrop, false);
foreach (var line in lines)
{
using (StreamReader sr = new StreamReader(Path.GetFullPath(line)))
{
var l = sr.ReadLine();
string[] data;
while (l != null)
{
data = l.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
l = sr.ReadLine();
tokens.Add(l);
}
}
}
for (int i = 0; i < tokens.Count - 1; i++)
{
dataGridView1.Rows[i].Cells[0].Selected = true;
dataGridView1.CurrentCell.Value = tokens[i];
}
}
The current code results in the line 2 being added to the datagridview only, with nothing else.
I would like to add each line into the first column of each row, depending on how many lines are in the text file.
Hopefully this makes sense, thanks a lot!
You can try this:
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
dataGridView1.Columns.Add("Value", "Value");
var files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
foreach ( var file in files )
{
var lines = File.ReadAllLines(Path.GetFullPath(file));
foreach ( string line in lines )
dataGridView1.Rows.Add(line.TrimEnd(','));
}
}
private void dataGridView1_DragEnter(object sender, DragEventArgs e)
{
if ( e.Data.GetDataPresent(DataFormats.FileDrop) )
e.Effect = DragDropEffects.Move;
else
e.Effect = DragDropEffects.None;
}
I am trying to write a program that contains a listview filled with 4 columns of data from a text file (Name, State, City, Zip in the 4 columns), and when the user clicks a name in the listview it displays the name and the phone number (which is in the text file) into 2 labels.
Here is my code so far:
namespace VendorsDictionary
{
public partial class VendorsDictionary : Form
{
public VendorsDictionary()
{
InitializeComponent();
}
private Dictionary<string,string> vendorPhones = new Dictionary<string,string>();
private void VendorsDictionary_Load(object sender, EventArgs e)
{
string currentLine;
string[] fields = new string[2];
StreamReader vendorReader = new StreamReader("Vendor.txt");
while (vendorReader.EndOfStream == false)
{
currentLine = vendorReader.ReadLine();
fields = currentLine.Split(',');
vendorPhones.Add(fields[1], fields[6]);
string[] name = { fields[1] };
string[] city = { fields[3] };
string[] state = { fields[4] };
string[] zipcode = { fields[5] };
for (int i = 0; i < name.Length; i++)
{
lvDisplay.Items.Add(new ListViewItem(new[] { name[i], city[i], state[i], zipcode[i] }));
}
}
vendorReader.Close();
}
private void lvDisplay_SelectedIndexChanged(object sender, EventArgs e)
{
if (lvDisplay.SelectedItems.Count>0)
{
ListViewItem item = lvDisplay.SelectedItems[0];
lblName.Text = item.SubItems[0].Text;
// lbPhone = ?
// lblPhone.Text = item.SubItems[].Text; - does not work because phone number is not in the listview
}
else
{
lblName.Text = string.Empty;
lblPhone.Text = string.Empty;
}
}
}
}
As of now I have everything working properly, except I cannot figure out how to get the phone number from the text file to display into the second label. To get name to display was easy enough because it was in the listview, but how would I get the phone number (last column in the text file) to display?
You are storing phone numbers of the vendors in a dictionary vendorPhones.
I am still unsure of the format and structure of the data stored in the file and why you loop for name.length.
If my assumption, that the vendor names are unique, you can get the phone number of the selected vendor from the dictionary as following.
private void lvDisplay_SelectedIndexChanged(object sender, EventArgs e)
{
if (lvDisplay.SelectedItems.Count>0)
{
ListViewItem item = lvDisplay.SelectedItems[0];
lblName.Text = item.SubItems[0].Text;
lblPhone.Text = vendorPhones[item.SubItems[0].Text]; // Get the phone number from dictionary by using the vendor name.
}
else
{
lblName.Text = string.Empty;
lblPhone.Text = string.Empty;
}
}
I have a problem when I try to display the list into the textbox. It only displays the last line from the list.txt file. I think for each new line it overwrites the first line from the textbox all the time ? thus showing only the last line from the file ?
what is it I need to think of to get it right ?
private void Form1_Load(object sender, EventArgs e)
{
const string f = "list.txt";
List<string> myList = new List<string>();
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
myList.Add(line);
}
}
foreach (string s in myList)
{
textBox1.Text = string.Join(Environment.NewLine, s);
}
}
Instead of this:
foreach (string s in myList)
{
textBox1.Text = string.Join(Environment.NewLine, s);
}
Try:
textBox1.Text = string.Join(Environment.NewLine, myList);
And also make sure multiline property of textbox1 is set to true.
Because every time, you assign directly to the Text property which will remove the previous one . Here is the fix . Make Multiline of textbox true.
private void Form1_Load(object sender, EventArgs e)
{
const string f = "list.txt";
List<string> myList = new List<string>();
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
myList.Add(line);
}
}
var listString = new StringBuilder()
foreach (string s in myList)
{
listString.Append(Environment.Newline)
listString.Append(s);
}
textBox1.Text = listString.ToString();
}
Based on my comment you can do this in one simple line by eliminating the foreach loop
textBox1.Text = string.Join(Environment.NewLine, myList.ToArray());
or just use the myList works the same
textBox1.Text = string.Join(Environment.NewLine, myList);