I am a complete newbie when it comes to programing. I followed the tutorial here to create a picture box. http://msdn.microsoft.com/en-u s/library/dd492135.aspx
I work in c#. Now i am going through and making some changes. Is there anyway to make a code so that there can be a next and back button?
Any help would be appriciated.
Thanks,
Rehan
If I understand well you want to have two buttons (Next, Back)
I make a little project and I will be happy if it helped you.
If you want this, continue reading:
First we have to declare imageCount and a List<string>: Imagefiles
so we have this
List<string> Imagefiles = new List<string>();
int imageCount = 0;
imageCount helps to change images using buttons
Imagefiles contains all Image paths of our photos
Now to change photos we have to declare a path first which wil contains all photos.
I use FolderBrowserDialog
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
findImagesInDirectory(fbd.SelectedPath);
}
}
You will see that I use findImagesInDirectory and this method doesnt exist. We have to create it.
This method will help us to filter all the files from the path and get only the image files
private void findImagesInDirectory(string path)
{
string[] files = Directory.GetFiles(path);
foreach(string s in files)
{
if (s.EndsWith(".jpg") || s.EndsWith(".png")) //add more format files here
{
Imagefiles.Add(s);
}
}
try
{
pictureBox1.ImageLocation = Imagefiles.First();
}
catch { MessageBox.Show("No files found!"); }
}
I use try because if no image files, with the above extension, exists code will break.
Now we declare all Image files (if they exists)
Next Button
private void nextImageBtn_Click(object sender, EventArgs e)
{
if (imageCount + 1 == Imagefiles.Count)
{
MessageBox.Show("No Other Images!");
}
else
{
string nextImage = Imagefiles[imageCount + 1];
pictureBox1.ImageLocation = nextImage;
imageCount += 1;
}
}
Previous Button
private void prevImageBtn_Click(object sender, EventArgs e)
{
if(imageCount == 0)
{
MessageBox.Show("No Other Images!");
}
else
{
string prevImage = Imagefiles[imageCount -1];
pictureBox1.ImageLocation = prevImage;
imageCount -= 1;
}
}
I believe my code help. Hope no bugs!
Related
I'm trying to create an application that searches for names in a listbox.
Basically, I have 2 .txt files (BoyNames, GirlNames) one file contains a set of boy names and the other girl names. Ive managed to display the boy names to boyNameListBox and girl names to girlNameListBox. please refer to the image ive attached. I'm trying to add the function where if the user types a boys name (in the boy textbox) and the name is lised in the list box, the app will return a messagebox showing "popular"; if the name is not listed, the app will show a messagebox showing not popular. I wish to include the same search function but for girl names. I'm very new to programming and your help will be very much appreciated. Thanks in advance!!
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void readButton_Click(object sender, EventArgs e)
{
{
//local variables
string line1;
//Catch Boy Names File
System.IO.StreamReader file = new System.IO.StreamReader(#"C:\Users\Harra\Documents\Visual Studio 2017\Projects\Name Search\BoyNames.txt");
//display items BoyNames file to Listbox
while ((line1 = file.ReadLine()) != null)
boyNameListbox.Items.Add(line1);
}
{
//local variales
string line2;
//Catch Girl Names File
System.IO.StreamReader file = new System.IO.StreamReader(#"C:\Users\Harra\Documents\Visual Studio 2017\Projects\Name Search\GirlNames.txt");
//display items GirlNames file to Listbox
while ((line2 = file.ReadLine()) != null)
girlNameListbox.Items.Add(line2);
}
}
private void boyButton_Click(object sender, EventArgs e)
{
}
private void girlButton_Click(object sender, EventArgs e)
{
}
}
Something like:
private void boyButton_Click(object sender, EventArgs e)
{
string boyname = boyTextBox.Text;
bool found = false;
for(int n = 0; n < boyNameListbox.Items.Count; n++)
{
if (boyNameListbox.Items[n] == boyname)
{
found = true;
break;
}
}
if (found)
MessageBox.Show("popular");
else
MessageBox.Show("not popular");
}
Mind you, I didn't code the whole form, so maybe small errors but hope you get the idea from this example. Hopefully this is close enough to get you started and be the accepted answer.
I have been working on this in my spare time, to no avail. I really could use a hand getting this to work.
I have a winform in C#. I am currently working with a listbox and a picturebox to display embedded image resources. I want to populate the listbox with just the file name, as the full path is longer than the width of the listbox can accommodate on my form.
Here is some code I was working with:
string[] x = System.IO.Directory.GetFiles(#"C:\Users\bassp\Dropbox\VS Projects\WindowsFormsApplication1\WindowsFormsApplication1\Resources\", "*.jpg");
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
foreach (string f in x)
{
string entry1 = Path.GetFullPath(f);
string entry = Path.GetFileNameWithoutExtension(f);
listBox1.DisplayMember = entry;
listBox1.ValueMember = entry1;
listBox1.Items.Add(entry);
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox1.ImageLocation = listBox1.SelectedItem.ToString();
}
If I populate the listbox with the full path,(entry1), things work pretty smooth other than not being able to see the image name you will be selecting due to the length of the full path.
When I try to populate the listbox with (entry), just the file names appear in the listbox, which is desireable, however, the image will no longer open on selection from the listbox.
How can I get this working correctly? Help is greatly appreciated.
Patrick
You're on the right track by setting the DisplayMember and ValueMember properties, but you'd need to make a few corrections, and it might not be necessary here.
Store the original directory path in a separate variable, then just combine that with the file name in your SelectedIndexChanged event to get the original file path.
string basePath =
#"C:\Users\bassp\Dropbox\VS Projects\WindowsFormsApplication1\WindowsFormsApplication1\Resources\";
string[] x = Directory.GetFiles(basePath, "*.jpg");
foreach (string f in x)
{
listBox1.Items.Add(Path.GetFileNameWithoutExtension(f));
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox1.ImageLocation =
Path.Combine(basePath, listBox1.SelectedItem.ToString()) + ".jpg";
}
Grant answer is perfectly ok for a simple task like this, but i'll explain another way that may be useful in other situations.
You can define a class to store your filenames and paths, something like:
class images
{
public string filename { get; set; }
public string fullpath { get; set; }
}
This way, your code could be like:
string[] x = System.IO.Directory.GetFiles(#"C:\Users\bassp\Dropbox\VS Projects\WindowsFormsApplication1\WindowsFormsApplication1\Resources\", "*.jpg");
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
List<images> imagelist=new List<images>();
foreach (string f in x)
{
images img= new images();
img.fullpath = Path.GetFullPath(f);
img.filename = Path.GetFileNameWithoutExtension(f);
imagelist.Add(img);
}
listBox1.DisplayMember = "filename";
listBox1.ValueMember = "fullpath";
listBox1.DataSource = imagelist;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox1.ImageLocation = ((images)listBox1.SelectedItem).fullpath;
}
I have not tested it,maybe it has any typo, but i hope you get the idea.
I'm using C3 VS 2012 express. Have a windows form with tab control.
On one of the tabs I would like to (and have setup) a datagridview (not sure if this is what I should use to accomplish what I need but seems like it would suit - open to other suggestions).
Please refer to the attached picture.
Basically I need to create a text file which will have the settings which are set and selected in the datagridview shown.
IMAGE REFERENCE
Currently a user can edit the field (which I would like to keep for some fields
I have marked the areas which I need answers for.
Here goes:
How to hide this index from the user and be able to select several computernames to be part of the group name PLUTO.
I need user to select a date and time here using datetimepicker.
How to make button read as BROWSE and place value in location cell (or same cell)
EDIT :
I have a part answer for this.. can place value in location cell now:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
OpenFileDialog fDialog = new OpenFileDialog();
if (fDialog.ShowDialog() != DialogResult.OK)
return;
System.IO.FileInfo fInfo = new System.IO.FileInfo(fDialog.FileName);
string strFileName = fInfo.Name;
string strFilePath = fInfo.DirectoryName;
string strFullFileName = fInfo.FullName;
textBox4.Text = strFullFileName;
//dataGridView1.Rows[e.RowIndex].Cells[3].Value = strFullFileName;
MessageBox.Show(strFileName + ", " + strFilePath + ", " + strFullFileName);
// Set value for some cell, assuming rowIndex refer to the new row.
dataGridView1.Rows[e.RowIndex].Cells[3].Value = strFullFileName;
}
Should I rather use an ADD button to allow user to add a new row ?
What code is required to remove an entry when user selects one to remove ?
Generate will be used to write to the file (Currently using fileappend) but what/how do I specify the element to append (eg is it colum/row number) easily ?
I finally solved most of this one by lot's of browsing and way too many late nights.
For number:
2. I decided not to use the date and time as it's just not necessary at this stage
3.A browse button was added using this:
//this is for button click event for clicking a cell in DGV
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 7)
{
//MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
// choose file here
OpenFileDialog fDialog = new OpenFileDialog();
if (fDialog.ShowDialog() != DialogResult.OK)
return;
System.IO.FileInfo fInfo = new System.IO.FileInfo(fDialog.FileName);
string strFileName = fInfo.Name;
string strFilePath = fInfo.DirectoryName;
string strFullFileName = fInfo.FullName;
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = strFullFileName;
dataGridView1.RefreshEdit();
I managed to add rows using an ADD button using this :
private void button17_Click(object sender, EventArgs e) // add rows DGV
{
this.dataGridView1.Rows.Insert("one", "two", "three", "four","etc");
dataGridView1.Rows.AddRange();
} //end add rows DGV
To remove rows I used a button and this code :
private void button18_Click(object sender, EventArgs e)
{
if (this.dataGridView1.SelectedRows.Count != -1)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
this.dataGridView1.Rows.Remove(row);
}
}
To remove a row I used a button and this code:
private void button19_Click(object sender, EventArgs e)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\foo\dgvTextFile.txt");//select name for created text file
try
{
string myTableLine = ""; //variable to hold each line
for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)//loop through table rows, one at a time
{
//now loop though each column for the row number we get from main loop
for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
{
myTableLine = myTableLine + dataGridView1.Rows[r].Cells[c].Value;
if (c != dataGridView1.Columns.Count - 1)
{
//set a delimiter by changinig the value between the ""
myTableLine = myTableLine + ",";
}
}
//write each line
file.WriteLine(myTableLine);
myTableLine = "";
}
file.Close();
System.Windows.Forms.MessageBox.Show("Grid Export Complete.All changes saved. Use create to create commands", "Program Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception err)
{
System.Windows.Forms.MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
file.Close();
}
}
I hope this helps someone else who is battling.
On a final note .. This proabably is not the BEST code but it worked for me and I hope that at least it will get you going if you're battling too.
I have one OpenFileDialog control that has Multiselect = true. Now I want to add each file to windows media player playlist but I have no idea how to do that and there is no good example on the internet.
if (ofdSong.ShowDialog() == DialogResult.OK)
{
foreach (string file in ofdSong.FileNames)
{
//Code to add file to the playlist
}
}
With help of DJ KRAZE that gave me the example link and JayJay who wrote that example, here is the solution.
WMPLib.IWMPPlaylist playlist = wmp.playlistCollection.newPlaylist("myplaylist");
WMPLib.IWMPMedia media;
if (ofdSong.ShowDialog() == DialogResult.OK)
{
foreach (string file in ofdSong.FileNames)
{
media = wmp.newMedia(file);
playlist.appendItem(media);
}
}
wmp.currentPlaylist = playlist;
wmp.Ctlcontrols.play();
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
var myPlayList = axWindowsMediaPlayer1.playlistCollection.newPlaylist("MyPlayList");
OpenFileDialog open = new OpenFileDialog();
open.Multiselect =true;
open.Filter = "All Files|*.*";
if(open.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
foreach(string file in open.FileNames)
{
var mediaItem = axWindowsMediaPlayer1.newMedia(file);
myPlayList.appendItem(mediaItem);
}
}
axWindowsMediaPlayer1.currentPlaylist = myPlayList;
}
to play multiple items: copy and paste and enjoy
I have 2 buttons (Button1 - Browse ; Button2 - Upload) and 1 textBox
Here is the scenario. When I click on Browse, it will open a window and will browse for a specific item.
The selected item will display on textbox.
private void Browse_Click(object sender, EventArgs e)
{
btnSample.Title = "Sample File Upload";
btnSample.InitialDirectory = #"c:\";
btnSample.Filter = "TIF|*.tif|JPG|*.jpg|GIF|*.gif|PNG|*.png|BMP|*.bmp|PDF|*.pdf|XLS|*.xls|DOC|*.doc|XLSX|*.xlsx|DOCX|*.docx";
btnSample.FilterIndex = 2;
btnSample.RestoreDirectory = true;
if (btnSample.ShowDialog() == DialogResult.OK)
{
textBox1.Text = btnSample.FileName;
}
}
When I click on the Upload Button the file on the textbox will be on the created folder.
I'm done with creating the folder. but my problem is how can i insert the selected file on the folder.
private void button4_Click(object sender, EventArgs e)
{
string path = #"C:\SampleFolder\NewFolder";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
MessageBox.Show("Successfully Created New Directory");
}
else
{
MessageBox.Show("Filename Exist");
}
}
var sourceFilePath = #"C:\temp\file.txt";
var destFilePath= #"C:\otherFolder\file.txt";
If you want to move the file:
File.Move(sourceFilePath, destFilePath);
If you want to copy the file
File.Copy(sourceFilePath, destFilePath);
easy huh?
ofcourse, you'd have to adapt the paths to your problem...