public void read_file(string fname)
{
filepath = fname;
TextReader input = File.OpenText(filepath);
line = input.ReadLine();
int[] ID = new int[6];
int[] x = new int[6];
int[] y = new int[6];
int xx, yy;
int i = 0;
image = AForge.Imaging.Image.FromFile(filename);
smal1 = AForge.Imaging.Image.FromFile(smallimg1);
smal2 = AForge.Imaging.Image.FromFile(smallimg2);
smal3 = AForge.Imaging.Image.FromFile(smallimg3);
smal4 = AForge.Imaging.Image.FromFile(smallimg4);
smal5 = AForge.Imaging.Image.FromFile(smallimg5);
smal6 = AForge.Imaging.Image.FromFile(smallimg6);
// int index = 0;
while (line != null && line != " ")
{
if (line == "change")
{
while (line != "end")
{
line = input.ReadLine();
line = line.Trim();
if (line != "end")
{
string[] parts = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
xx = int.Parse(parts[0]);
yy = int.Parse(parts[1]);
image.SetPixel(xx, yy, Color.Blue);
}
}
line = input.ReadLine();
}
else
{
string[] parts2 = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
ID[i] = int.Parse(parts2[0]);
x[i] = int.Parse(parts2[1]);
y[i] = int.Parse(parts2[2]);
line = input.ReadLine();
if(ID[i]==1)
{
pictureBox2.Size = smal1.Size;
pictureBox2.Image = smal1;
}
else if (ID[i] == 2)
{
pictureBox3.Size = smal2.Size;
pictureBox3.Image = smal2;
}
else if (ID[i] == 3)
{
pictureBox4.Size = smal3.Size;
pictureBox4.Image = smal3;
}
else if (ID[i] == 4)
{
pictureBox5.Size = smal4.Size;
pictureBox5.Image = smal4;
}
else if (ID[i] == 5)
{
pictureBox6.Size = smal5.Size;
pictureBox6.Image = smal5;
}
else if (ID[i] == 6)
{
pictureBox7.Size = smal6.Size;
pictureBox7.Image = smal6;
}
i++;
}
}
// pictureBox2.BackColor = Color.SteelBlue;
// pictureBox2.Image = smal;
// pictureBox2.Size = smal.Size;
pictureBox1.Image = image;
pictureBox1.Size = image.Size;
//pictureBox2.Hide();
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Start_Click(object sender, EventArgs e)
{
capture_flag = true;
start_reading();
}
private void Stop_Click(object sender, EventArgs e)
{
capture_flag = false;
}
private void start_reading()
{
string filen = "F:/4th year/1st Term/sensor network/proj/reconstructscene/stream.txt";
read_file(filen);
filen = "F:/4th year/1st Term/sensor network/proj/reconstructscene/stream1.txt";
read_file(filen);
filen = "F:/4th year/1st Term/sensor network/proj/reconstructscene/stream2.txt";
read_file(filen);
}
private void close_Click(object sender, EventArgs e)
{
this.Dispose();
}
in the above code i'm trying to call the function read_file several times but it's not working
the form just wait until the end then draw once .
note in the original project i'll take the file name from another part of the poject and i may call the function like
while (capture_flag)
{
filen = file;
read_file(filen);
}
which not working for the same reason
The reason that the changes doesn't show up whlie the method is running, is that the main thread is busy running the method so it's not listening to messages. The updates happens in the form of messages that are placed on the message queue, so when the main thread can't handle the messages, there are no updates.
You can use the Refresh method to force a redraw of the control while in the middle of the method:
pictureBox2.Size = smal1.Size;
pictureBox2.Image = smal1;
pictureBox2.Refresh();
Related
How do I change the autocomplete on a TextBox? I want that when I type a string, the box suggest items containing that string instead of starting with.
My code is:
class MyClass
{
private AutoCompleteStringCollection autoCompleteList = new AutoCompleteStringCollection();
public MyClass()
{
InitializeComponent();
autoCompleteList.AddRange(ListNames.Select(x=>x.Name).ToArray());
textBoxName.AutoCompleteCustomSource = autoCompleteList;
textBoxName.AutoCompleteSource = AutoCompleteSource.CustomSource;
textBoxName.AutoCompleteMode = AutoCompleteMode.Suggest;
textBoxName.KeyDown += TextBoxtextName_KeyDown;
}
private void TextBoxClient_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
this.Name = (sender as TextBox).Text;
}
}
}
What I want:
Looking at your code you have everything you need but 1 line of code. That line is:
This will only work if the start of a string is entered
//Suggestion only
textBoxName.AutoCompleteMode = AutoCompleteMode.Suggest;
//Suggest and autocomplete
textBoxName.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
This will work as a contains method but works with a custom control
You can also make a custom textbox control that fits your needs.
Custom textbox class:
public class AutoCompleteTextBox : TextBox
{
private ListBox _listBox;
private bool _isAdded;
private String[] _values;
private String _formerValue = String.Empty;
public AutoCompleteTextBox()
{
InitializeComponent();
ResetListBox();
}
private void InitializeComponent()
{
_listBox = new ListBox();
this.KeyDown += this_KeyDown;
this.KeyUp += this_KeyUp;
}
private void ShowListBox()
{
if (!_isAdded)
{
Parent.Controls.Add(_listBox);
_listBox.Left = Left;
_listBox.Top = Top + Height;
_isAdded = true;
}
_listBox.Visible = true;
_listBox.BringToFront();
}
private void ResetListBox()
{
_listBox.Visible = false;
}
private void this_KeyUp(object sender, KeyEventArgs e)
{
UpdateListBox();
}
private void this_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Enter:
case Keys.Tab:
{
if (_listBox.Visible)
{
Text = _listBox.SelectedItem.ToString();
ResetListBox();
_formerValue = Text;
this.Select(this.Text.Length, 0);
e.Handled = true;
}
break;
}
case Keys.Down:
{
if ((_listBox.Visible) && (_listBox.SelectedIndex < _listBox.Items.Count - 1))
_listBox.SelectedIndex++;
e.Handled = true;
break;
}
case Keys.Up:
{
if ((_listBox.Visible) && (_listBox.SelectedIndex > 0))
_listBox.SelectedIndex--;
e.Handled = true;
break;
}
}
}
protected override bool IsInputKey(Keys keyData)
{
switch (keyData)
{
case Keys.Tab:
if (_listBox.Visible)
return true;
else
return false;
default:
return base.IsInputKey(keyData);
}
}
private void UpdateListBox()
{
if (Text == _formerValue)
return;
_formerValue = this.Text;
string word = this.Text;
if (_values != null && word.Length > 0)
{
string[] matches = Array.FindAll(_values,
x => (x.ToLower().Contains(word.ToLower())));
if (matches.Length > 0)
{
ShowListBox();
_listBox.BeginUpdate();
_listBox.Items.Clear();
Array.ForEach(matches, x => _listBox.Items.Add(x));
_listBox.SelectedIndex = 0;
_listBox.Height = 0;
_listBox.Width = 0;
Focus();
using (Graphics graphics = _listBox.CreateGraphics())
{
for (int i = 0; i < _listBox.Items.Count; i++)
{
if (i < 20)
_listBox.Height += _listBox.GetItemHeight(i);
// it item width is larger than the current one
// set it to the new max item width
// GetItemRectangle does not work for me
// we add a little extra space by using '_'
int itemWidth = (int)graphics.MeasureString(((string)_listBox.Items[i]) + "_", _listBox.Font).Width;
_listBox.Width = (_listBox.Width < itemWidth) ? itemWidth : this.Width; ;
}
}
_listBox.EndUpdate();
}
else
{
ResetListBox();
}
}
else
{
ResetListBox();
}
}
public String[] Values
{
get
{
return _values;
}
set
{
_values = value;
}
}
public List<String> SelectedValues
{
get
{
String[] result = Text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
return new List<String>(result);
}
}
}
Usage:
string[] nameArray = { "name1", "name2", "name3", "bla name" };
AutoCompleteTextBox tb = new AutoCompleteTextBox();
tb.Values = nameArray;
tb.Location = new Point(10,10);
tb.Size = new Size(25,75);
this.Controls.Add( tb );
I got the code for the custom control from: SO Question - Autocomplete contains
My C# classes will create a GUI that takes in csv files and plot a line graph accordingly. Currently, my graphs are plotted and saved using the GUI file dialog.
What I am trying to do now is to read, plot and save the graph using command-line instead (NO GUI needed).
May I know how could I call my Read and Plot classes using the "-f" flag (file path, can have multiple csv file) and save the plotted graph using the "-o" flag (output file path, only 1 file produced)?
Thanks.
You can use this:
class Program:
static class Program
{
[System.Runtime.InteropServices.DllImport("kernel32.dll")] // ### Edit 3 ###
static extern bool AttachConsole(int dwProcessId); // ### Edit 3 ###
/// <summary>The main entry point for the application.</summary>
[STAThread]
static void Main(string[] args)
{
// redirect console output to parent process;
// must be before any calls to Console.WriteLine()
AttachConsole(-1);// ### Edit 3 ###
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//program.exe -f c:\\desktop\\1.csv -o c:\\desktop\\1.png
var inputFile = new List<string>();
string outputFile = null;
if (args.Length > 0)
{
for (int i = 0; i < args.Length; i++)
{
string a = args[i].ToLower();
switch (a)
{
case "-f":
for (i = i + 1; i < args.Length ; i++)
{
string f = args[i]; if (f.StartsWith("-")) { i--; break; }
inputFile.Add(f); //get next arg as inputFile
}
break;
case "-o":
outputFile = args[++i]; //get next arg as outputFile
break;
}
}
if (inputFile.Count > 0 && outputFile != null)
{
var form = new Form2(); //specify your form class
form.showErrorsInConsole = true; // ### Edit 3 ###
//form.Visible = true;
form.DoReadFiles(inputFile.ToArray());
form.DoPlot();
form.SavePic(outputFile);
form.Dispose();
return;
}
}
//else
Application.Run(new Form2()); //show GUI
//MessageBox.Show("Args:\r\n" + s);
}
}
Form class (the form conatining your chart, in my code it is Form2):
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
List<Read> rList = new List<Read>();
public bool showErrorsInConsole = false; //### Edit 3 ###
public void DoReadFiles(string[] fileNames)
{
try
{
rList.Clear();
foreach (String file in fileNames) //if ((myStream = ff.OpenFile()) != null)
{
Read r = new Read(file);
rList.Add(r);
}
}
catch (Exception err)
{
//Inform the user if we can't read the file
if (showErrorsInConsole) //### Edit 3 ###
Console.WriteLine("\r\n *** Error: " + err.Message); //### Edit 3 ###
else
MessageBox.Show(err.Message);
}
}
public void DoPlot(int indX = 0, int indY = 1)
{
Plot.Draw(chart, rList, indX, indY);
}
public void SavePic(string outputFile)
{
bool isPng = outputFile.EndsWith(".png", StringComparison.OrdinalIgnoreCase);
chart.SaveImage(outputFile, isPng ? ChartImageFormat.Png : ChartImageFormat.Jpeg);
}
void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog ff = new OpenFileDialog();
ff.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); //"C:\\";
ff.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
ff.Multiselect = true;
ff.FilterIndex = 1;
ff.RestoreDirectory = true;
if (ff.ShowDialog() == DialogResult.OK)
{
try
{
DoReadFiles(ff.FileNames);
//Populate the ComboBoxes
if (rList.Count > 0)
{
string[] header = rList[0].header; //header of first file
xBox.DataSource = header;
yBox.DataSource = header.Clone(); //without Clone the 2 comboboxes link together!
}
if (yBox.Items.Count > 1) yBox.SelectedIndex = 1; //select second item
}
catch (Exception err)
{
//Inform the user if we can't read the file
MessageBox.Show(err.Message);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
DoPlot(xBox.SelectedIndex, yBox.SelectedIndex);
}
} //end class Form2
class Read:
public class Read
{
public int nLines { get; private set; }
public int nColumns { get; private set; }
public string[] header { get; private set; }
public float[,] data { get; private set; }
public string fileName { get; set; }
public string[] section { get; private set; }
public Read(string file)
{
string[] pieces;
fileName = Path.GetFileName(file);
string[] lines = File.ReadAllLines(file); // read all lines
if (lines == null || lines.Length < 2) return; //no data in file
header = lines[0].Split(','); //first line is header
nLines = lines.Length - 1; //first line is header
nColumns = header.Length;
//read the numerical data and section name from the file
data = new float[nLines, nColumns - 1]; // 1 less than nColumns as last col is sectionName
section = new string[nLines];
for (int i = 0; i < nLines; i++)
{
pieces = lines[i + 1].Split(','); // i(+1) is because first line is header
if (pieces.Length != nColumns) { MessageBox.Show("Invalid data at line " + (i + 2) + " of file " + fileName); return; }
for (int j = 0; j < nColumns - 1; j++)
{
float.TryParse(pieces[j], out data[i, j]); //data[i, j] = float.Parse(pieces[j]);
}
section[i] = pieces[nColumns - 1]; //last item
}
}
}
class Plot:
public class Plot
{
public static void Draw(Chart chart, List<Read> rList, int indX = 0, int indY = 1)
{
chart.Series.Clear(); //ensure that the chart is empty
chart.Legends.Clear();
Legend myLegend = chart.Legends.Add("myLegend");
myLegend.Title = "myTitle";
Color[] colors = new Color[] { Color.Black, Color.Blue, Color.Red, Color.Green, Color.Magenta, Color.DarkCyan, Color.Chocolate, Color.DarkMagenta };
var sectionColors = new Dictionary<string, int>();
bool separateSections = (rList.Count == 1); // #Edit: 4
int i = 0;
int iColor = -1, maxColor = -1;
foreach (Read rr in rList)
{
float[,] data = rr.data;
int nLines = rr.nLines;
int nColumns = rr.nColumns;
string[] header = rr.header;
chart.Series.Add("Series" + i);
chart.Series[i].ChartType = SeriesChartType.Line;
chart.Series[i].LegendText = rr.fileName; // #Edit: 4
if (separateSections) chart.Series[i].IsVisibleInLegend = false; // #Edit: 4
chart.ChartAreas[0].AxisX.LabelStyle.Format = "{F2}";
chart.ChartAreas[0].AxisX.Title = header[indX];
chart.ChartAreas[0].AxisY.Title = header[indY];
for (int j = 0; j < nLines; j++)
{
int k = chart.Series[i].Points.AddXY(data[j, indX], data[j, indY]);
if (separateSections) // #Edit: 4
{
string curSection = rr.section[j];
if (sectionColors.ContainsKey(curSection))
{
iColor = sectionColors[curSection];
}
else
{
maxColor++;
iColor = maxColor; sectionColors[curSection] = iColor;
}
chart.Series[i].Points[k].Color = colors[iColor];
}
}
i++; //series#
} //end foreach rr
//fill legend based on series
foreach (var x in sectionColors)
{
string section = x.Key;
iColor = x.Value;
myLegend.CustomItems.Add(colors[iColor], section); //new LegendItem()
}
}
}
If you are looking for something simple then you can just have a loop and get the values like this:
string f=null;
string o=null;
for (var i = 0; i < args.Length; i++)
{
if (args[i] == "-f") { f = args[i + 1]; }
else if (args[i] == "-o") { o = args[i + 1]; }
}
if (f != null)
{
}
if (o != null)
{
}
You can use command parser libraries. Command Line Parser ( http://commandline.codeplex.com/ ) is very easy to use.
[Option("f", "input", Required = true]
public string InputFile { get; set; }
[Option("o", "output", Required = true]
public string OutputFile { get; set; }
I have a program where i need to count how many females and Males are in the file that has been read into the richtextbox, but I'm not sure how to do that , in the file has the name, gender,specific job . I have to count between 15 different people
for example : " Donna,Female,Human Resources.",
This is what I have so far:
private void Form1_Load(object sender, EventArgs e)
{
StreamReader sr;
richTextBox1.Clear();
sr = new StreamReader("MOCK_DATA.txt");
string data;
while (!sr.EndOfStream)
{
data = sr.ReadLine();
richTextBox1.AppendText(data + "\n");
}
}
private void button1_Click(object sender, EventArgs e)
{
string[] data = richTextBox1.Text.Split(',');
for (int n = 0; n < data.Length; n++)
{
if (data[n] == richTextBox1.Text)
n++;
To get the plain text from a RichTextBox (stolen from this article):
string StringFromRichTextBox(RichTextBox rtb)
{
TextRange textRange = new TextRange(
// TextPointer to the start of content in the RichTextBox.
rtb.Document.ContentStart,
// TextPointer to the end of content in the RichTextBox.
rtb.Document.ContentEnd
);
// The Text property on a TextRange object returns a string
// representing the plain text content of the TextRange.
return textRange.Text;
}
Basic word counting routine:
int CountWord(string textToSearch, string word)
{
int count = 0;
int i = textToSearch.IndexOf(word);
while (i != -1)
{
count++;
i = textToSearch.IndexOf(word, i+1);
}
return count;
}
Putting it together:
var plainText = StringFromRichTextBox(richTextBox1);
var countOfMale = CountWord(plainText, "Male");
var countOfFemale = CountWord(plainText, "Female");
private void toolStripButton81_Click(object sender, EventArgs e)
{
string findterm = string.Empty;
findterm = toolStripTextBox2.Text;
// the search term - specific word
int loopCount = 0;
// count the number of instance
int findPos = 0;
// depending on checkbox settings
// whole word search or match case etc
try
{
while (findPos < GetRichTextBox().Text.Length)
{
if (wholeWordToolStripMenuItem.CheckState == CheckState.Checked & matchCaseToolStripMenuItem.CheckState == CheckState.Checked)
{
findPos = GetRichTextBox().Find(findterm, findPos, RichTextBoxFinds.WholeWord | RichTextBoxFinds.MatchCase);
}
else if (wholeWordToolStripMenuItem.CheckState == CheckState.Checked)
{
findPos = GetRichTextBox().Find(findterm, findPos, RichTextBoxFinds.WholeWord);
}
else if (matchCaseToolStripMenuItem.CheckState == CheckState.Checked)
{
findPos = GetRichTextBox().Find(findterm, findPos, RichTextBoxFinds.MatchCase);
}
else
{
findPos = GetRichTextBox().Find(findterm, findPos, RichTextBoxFinds.None);
}
GetRichTextBox().Select(findPos, toolStripTextBox2.Text.Length);
findPos += toolStripTextBox2.Text.Length + 1;
loopCount = loopCount + 1;
}
}
catch
{
findPos = 0;
}
// at the end bring the cursor at the beginning of the document
GetRichTextBox().SelectionStart = 0;
GetRichTextBox().SelectionLength = 0;
GetRichTextBox().ScrollToCaret();
// Show the output in statusbar
toolStripStatusLabel2.Text = "Instances: " + loopCount.ToString();
}
I am trying to read in data from two serial ports, and plot each curve over time, on the same graph. However, when I do this, it connects the curves. How do I keep the two data sets separate but on the same graph? I've seen a lot of solutions using masterPane, however, when I try to use it, my program says that there is no materpane in zedgraph.
Here is the relevant code:
GraphPane myPane2;
PointPairList Oz1time = new PointPairList();
myPane2 = zedGraphControl2.GraphPane;
myPane2.Title = "Data vs Time Plots";
myPane2.XAxis.Title = "Elapsed Minutes";
myPane2.YAxis.Title = "Ozone Data";
private void UpdateData3(string line)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new UpdateDataDelegate(UpdateData3), new object[] { line });
}
else
{
if (chk_DISPLAY_3.Checked == true)
{
timer3.Interval = (30000);
timer3.Start();
OZ1lastdatatime = DateTime.Now;
count++;
if (count > 7)
{
count = 0;
TextBox_3.Text = "";
TextBox_3.AppendText(line);
}
else
{
TextBox_3.AppendText(line);
}
}
if (chk_SAVE_FILE_3.Checked == true)
{
StoreData3.Write(line);
StoreData3.Flush();
}
if (chk_PLOT_1.Checked == true)
{
string[] blahArray = line.Split(new char[] { ',' });
//string blaharray = Convert.ToDouble(blahArray[2]).ToString("F4");
int column_data = Convert.ToInt32(textBox3.Text);
double oz1 = Convert.ToDouble(blahArray[column_data]);
//TextBox_3.Text = Convert.ToString(oz1);
TimeSpan span = DateTime.UtcNow - startDateTimeOfProgram;
double elapsedMinutes = span.TotalMinutes;
Oz1time.Add(elapsedMinutes,oz1);
zedGraphControl2.AxisChange();
zedGraphControl2.GraphPane.AddCurve("", Oz1time , Color.Blue);
zedGraphControl2.Refresh();
}
}
}
private void UpdateData4(string line)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new UpdateDataDelegate(UpdateData4), new object[] { line });
}
else
{
Console.WriteLine(line);
if (chk_DISPLAY_4.Checked == true)
{
timer4.Interval = (30000);
timer4.Start();
OZ2lastdatatime = DateTime.Now;
count++;
if (count > 7)
{
count = 0;
TextBox_4.Text = "";
TextBox_4.AppendText(line);
}
else
{
TextBox_4.AppendText(line);
}
}
if (chk_SAVE_FILE_4.Checked == true)
{
StoreData4.Write(line);
StoreData4.Flush();
}
if (chk_PLOT_2.Checked == true)
{
string[] blahArray = line.Split(new char[] { ',' });
//string blaharray = Convert.ToDouble(blahArray[2]).ToString("F4");
int column_data = Convert.ToInt32(textBox4.Text);
double oz2 = Convert.ToDouble(blahArray[column_data]);
//TextBox_3.Text = Convert.ToString(oz1);
TimeSpan span = DateTime.UtcNow - startDateTimeOfProgram;
double elapsedMinutes = span.TotalMinutes;
Oz1time.Add(elapsedMinutes, oz2);
zedGraphControl2.AxisChange();
zedGraphControl2.GraphPane.AddCurve("", Oz1time, Color.Green);
zedGraphControl2.Refresh();
}
}
}
The main problem appears to be that you are using the same PointPairList, Oz1time, to create both curves. Instead, try creating two separate PointPairLists, one for each curve.
Some relevant code bits:
PointPairList Oz2time = new PointPairList();
...
Oz2time.Add(elapsedMinutes, oz2);
...
zedGraphControl2.GraphPane.AddCurve("", Oz2time, Color.Green);
i have the code in which i m displaying directories and files from the computer.i can open them by using folerbrowser. so far so good but now i want to add backward and forward button so that i can see the previous folder or file selected and go fwd to.
public partial class ListView : Form
{
public ListView()
{
InitializeComponent();
comboBox1.SelectedIndex = 2;
}
private void PopulateListView()
{
listView1.Clear();
//headers listview
listView1.Columns.Add("File Name", 200);
listView1.Columns.Add("Size", 80);
listView1.Columns.Add("Last Accessed", 110);
ExtensionsHolder.Clear();
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
//int thefile = 0;
string[] dirData = new string[3];
string[] filData = new string[3];
string[] files = Directory.GetFiles(folderBrowser.SelectedPath);
var folders = Directory.GetDirectories(folderBrowser.SelectedPath)
.Where(d => !new DirectoryInfo(d).Attributes.HasFlag(FileAttributes.System | FileAttributes.Hidden));
try
{
//THIS IS THE ITERATION TO GET SUBDIRECTORIES
foreach (string dir in folders)
{
//string name = Path.g;
dirData[0] = dir.ToString();
dirData[1] = dir.Length.ToString();
dirData[2] = File.GetLastAccessTime(dir).ToString();
ListViewItem lv = new ListViewItem(dirData, imageList1.Images.Count);
lv.Tag = dir;
imageList1.Images.Add(IconExtractor.Form1.GetFolderIcon(IconExtractor.IconSize.Small, IconExtractor.FolderType.Closed));
listView1.SmallImageList = imageList1;
listView1.Items.Add(lv);
}
//THIS IS ITERATION FOR FILES OF THE DIRECTORY
foreach (string file in files)
{
FileInfo finfo = new FileInfo(file);
FileAttributes fatr = finfo.Attributes;
string name = Path.GetFileNameWithoutExtension(file);
filData[0] = name;
filData[1] = finfo.Length.ToString();
filData[2] = File.GetLastAccessTime(file).ToString();
ListViewItem lv = new ListViewItem(filData, imageList1.Images.Count - 1);
lv.Tag = file;
string extension = Path.GetExtension(file);
if (!extension.Equals("") && !ExtensionsHolder.Contains(extension))
{
ExtensionsHolder.Add(extension);
imageList1.Images.Add(BlackFox.Win32.Icons.IconFromExtensionShell(extension, BlackFox.Win32.Icons.SystemIconSize.Small));
}
listView1.SmallImageList = imageList1;
listView1.Items.Add(lv);
}
}
catch (UnauthorizedAccessException)
{
listView1.Items.Add("Access denied");
}
}
}
List<string> ExtensionsHolder = new List<string>();
private void textBox1_TextChanged(object sender, EventArgs e)
{
string chattextbox=textBox1.Text;
}
private void button1_Click(object sender, EventArgs e)
{
PopulateListView();
textBox1.Text = folderBrowser.SelectedPath;
}
private void listView1_ItemActivate(object sender, EventArgs e)
{
try
{
string sPath = listView1.FocusedItem.Tag.ToString();
Process.Start(sPath);
}
catch(Exception Exc) { MessageBox.Show(Exc.ToString()); }
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboBox1.SelectedIndex == 0)
listView1.View = View.LargeIcon;
if(comboBox1.SelectedIndex==1)
listView1.View = View.SmallIcon;
if(comboBox1.SelectedIndex==2)
listView1.View = View.Details;
if (comboBox1.SelectedIndex == 3)
listView1.View = View.List;
else if (comboBox1.SelectedIndex == 5)
listView1.View = View.Tile;
}
private void Farward_Click(object sender, EventArgs e)
{
//Stack fpath = new Stack();
Stack<string> itemindex = new Stack<string>();
itemindex.Push(listView1.SelectedIndices.ToString());
itemindex.Push("two");
itemindex.Push("three");
//itemindex.Push("four");
//itemindex.Push("five");
// A stack can be enumerated without disturbing its contents.
foreach (string number in itemindex)
{
Console.WriteLine(number);
}
Console.WriteLine("\nPopping '{0}'", itemindex.Pop());
Console.WriteLine("Peek at next item to destack: {0}",
itemindex.Peek());
Console.WriteLine("Popping '{0}'", itemindex.Pop());
}
private void Back_Click(object sender, EventArgs e)
{
int i = 0;
for (i = 0; i < listView1.Items.Count; i++)
{
if (i != 0)
{
listView1.Items[i - 1].SubItems[1].Text = "Selected";
// txtPath.Text = listView1.Items[i - 1].Text;
}
}
}
private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (listView1.SelectedIndices.Count > 0)
MessageBox.Show("selected index"+ listView1.SelectedIndices[0]);
else
MessageBox.Show("No item selected");
}
}
}
Forward . . .
private void Farward_Click(object sender, EventArgs e)
{
//Stack fpath = new Stack();
Stack<string> itemindex = new Stack<string>();
itemindex.Push(listView1.SelectedIndices.ToString());
itemindex.Push("two");
itemindex.Push("three");
//itemindex.Push("four");
//itemindex.Push("five");
// A stack can be enumerated without disturbing its contents.
foreach (string number in itemindex)
{
Console.WriteLine(number);
}
Console.WriteLine("\nPopping '{0}'", itemindex.Pop());
Console.WriteLine("Peek at next item to destack: {0}",
itemindex.Peek());
Console.WriteLine("Popping '{0}'", itemindex.Pop());
}
Backward . . .
private void Back_Click(object sender, EventArgs e)
{
int i = 0;
for (i = 0; i < listView1.Items.Count; i++)
{
if (i != 0)
{
listView1.Items[i - 1].SubItems[1].Text = "Selected";
// txtPath.Text = listView1.Items[i - 1].Text;
}
}
}
It's kind of hard to do this because your code contains a lot of unecessary UI stuff. Anyway this is how I did it . . .
Let lvItems be our ListView, and allow A B C D be the elements in our ListView. We select only A, C, D . . .
lvItems.SelectedIndices.Add(0);
lvItems.SelectedIndices.Add(2);
lvItems.SelectedIndices.Add(3);
So in our Next button, we define the Click event as follows . . .
Stack<string> sItms = new Stack<string>();
for (int i = 0; i < lvItems.SelectedIndices.Count; ++i)
{
int idx = lvItems.SelectedIndices[i];
string itm = lvItems.Items[idx].ToString();
sItms.Push(itm);
}
// Our set contains D, C, A
// Peek() will display D
And in our Back button, we define the Click event as follows . . .
Stack<string> sItms = new Stack<string>();
for (int i = 0; i < lvItems.SelectedIndices.Count; ++i)
{
int idx = lvItems.SelectedIndices[(lvItems.SelectedIndices.Count - 1)-i];
string itm = lvItems.Items[idx].ToString();
sItms.Push(itm);
}
// Our Set Contains A, C, D
// Peek() will display A
Is this what you're looking for? Tell me how it goes . . .