private void accView_CellClick(object sender, DataGridViewCellEventArgs e)I have an application with a database. It is an inventory application. When the user goes to add an entry to a table they have the option to upload a photo. It is not required. Once they add the new item without a photo successfully then should be able to go to the main form and select the row on the datagridview and it will populate some labels with data based on what is selected.
The problem starts when they select a row without a photo uploaded to the database. It throws an ArgumentException stating that The path is not of a legal form. Below is my code. I am having a hard time getting around this. If a row is selected that does not have a photo, the picture box should just show the default photo...
private void accView_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1)
return;
if (!accView.Rows[e.RowIndex].IsNewRow)
{
//Visual Studio shows the error on the line of code below.
accPictureBox.Image = Image.FromFile(accView.Rows[e.RowIndex].Cells[10].Value.ToString(), true);
}
}
Update:
private void accView_CellClick(object sender, DataGridViewCellEventArgs e)
{
string defImage = (new System.Uri(System.Reflection.Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
string imageDir = Path.GetDirectoryName(defImage);
string fullPath = Path.Combine(imageDir, #"C:\Users\Brandon\Documents\Visual Studio 2013\Projects\Firearm Asset Management\Firearm Asset Management\bin\Beta\Images\DefaultImage4.jpg");
var path = accView.Rows[e.RowIndex].Cells[10].Value;
//Syntax Error on line below for invalid arguments.
if (string.IsNullOrEmpty(path))
{
//set the default path
path = fullPath;
}
//Syntax Error on line below for invalid arguments.
accPictureBox.Image = Image.FromFile(path, true)
}
Where there's no image uploaded, then presumably
accView.Rows[e.RowIndex].Cells[10].Value
will be null or an empty string. Therefore, check
string defImage = (new System.Uri(System.Reflection.Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
string imageDir = Path.GetDirectoryName(defImage);
string fullPath = Path.Combine(imageDir, #"./Images/DefaultImage4.jpg");
string path = string.Empty;
if (accView.Rows[e.RowIndex].Cells[10].Value != null)
path = accView.Rows[e.RowIndex].Cells[10].Value.ToString();
//Syntax Error on line below for invalid arguments.
if (string.IsNullOrEmpty(path))
{
//set the default path
path = fullPath;
}
//Syntax Error on line below for invalid arguments.
accPictureBox.Image = Image.FromFile(path, true)
I imagine that cell[10] is where the image path should be. However, if the user has not uploaded an image you will not have a path.
I would first check the value of cell[10] and if the value is a properly formed path then I would assign it to accPictureBox.Image
Related
I am working on a program for personal use that will automatically sort a grocery list (from file) into a particular order. I want the program to open the file, read each line, and determine if each line contains certain words. For example, a line could contain "chicken breasts," and the program would just recognize that it contained "chicken." The idea is to have the program automatically order my list so that I'm not running back and forth getting items when I go to the store. Currently the external file line must have the exact text "chicken" for the program to recognize it ("chicken breasts" will not be recognized). Here is the section that I believe is giving me trouble:
if (groceries.Contains("chicken"))
{
chicken = "Chicken";
lstItems.Items.Add(chicken);
}
Groceries is an array with each element being a line from the file (I think I created it correctly). Below is the entire code:
private void btnImport_Click(object sender, EventArgs e)
{
//Grocery items
string chicken;
//StreamReader variable
StreamReader readFile;
string filePath;
//Counter variable
int index = 0;
//Display open file dialog box
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//Set filepath as a variable
filePath = openFileDialog1.FileName;
// Assign the file as a variable
readFile = File.OpenText(filePath);
//Count lines in file and create array
int lineCount = File.ReadLines(filePath).Count();
string[] groceries = new string[lineCount];
//Read file's contents
while (index < groceries.Length && !readFile.EndOfStream)
{
groceries[index] = readFile.ReadLine();
index++;
if (groceries.Contains("chicken"))
{
chicken = "Chicken";
//Display items in label
lstItems.Items.Add(chicken);
}
}
//Close file
readFile.Close();
}
}
When the program is run, it will add "Chicken" to the listbox the same number of times as the number of lines in the file, even though only one line actually contains "chicken." My question is: How can I make it pick out the keyword from a longer line of text, and why is it adding the item more than once? Thanks!
Edit
(Sorry I don't know how to attach a file here)
I am currently importing a .txt file with the following data:
chicken
fish
Frosted Flakes cereal
pork tenderloin
ground beef
First, you need to remove the redundant openFileDialog1.ShowDialog();. And access the elements in groceries by index. Then add additional conditions to exclude rows that contain "chicken breasts". Note that index++ is executed after the if statement.
// define a varibale
bool chickenadded = false;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
// remove the redundant ShowDialog
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// code omitted ...
//Read file's contents
while (index < groceries.Length && !readFile.EndOfStream)
{
groceries[index] = readFile.ReadLine();
// check here
if (groceries[index].Contains("chicken") && !chickenadded /*&& !groceries[index].Contains("chicken breasts")*/)
{
chicken = "Chicken";
lstItems.Items.Add(chicken);
// set to true
chickenadded = true;
// another way is not define boolean, just use "break"
break;
}
// reset index here
index++;
}
Disregarding any other problem or what the overall goal of the application is. You forgot to look at the actual line
if (groceries[index].Contains("chicken"))
It's worth a note that you should likely be using File.ReadLines or File.ReadAllLines instead. As it gives you a collection or enumerable to work with
I want to know how i can get the picture from the project folder and if User not choice any picture i can save it as Default persoanl picture
i use this code for create name , path and save ( if i have any pic eveything as fine, if user not choice any picture my code broken
//Set Image Name
string imageName = txtNationalCode.Text.ToString() + Path.GetExtension(imgPersonalPhoto.ImageLocation);
//Set Image Path
string ImageLocation = imgPersonalPhoto.ImageLocation;
//Save Image
string path = Application.StartupPath + "/Images/";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
try
{
if (imgPersonalPhoto.Image != null)
{
imgPersonalPhoto.Image.Save(path + imageName);
}
else
{
//i dont know how set some picture for default and save it ! ( i have 1 picture for background picturebox
imgPersonalPhoto.Image.Save(path + imageName);
}
}
catch
{
RtlMessageBox.Show("Add Picture for this Personal please ");
}
i will try add some picture in my app Folder
but if i send my app to other this folder not exist !
Set the image in Form_Load using Image.FromFile. This way it will always set the default image when the form is loaded.
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(#"C:\...");
}
I have to create a file manager from scratch and im stuck in the begining.
It must show all drives name letter first.
Then onclick shows folders an files in childnode and ... .
Here is my question:
How can i get node name (as a string) which is clicked ?
Is it the right way to doing this?
Here i first get drives name letter:
var drives = DriveInfo.GetDrives();
for (var i = 0; i < drives.Count(); i++)
{
var drivesletter = drives[i].Name;
treeView1.Nodes.Add(drivesletter);
}
Here i created a method, when you click on each node, node name should be saved in a Variable, then it will get list of all files and folders in it and add them to the node that we clicked on it:
private void treeView1_Click(object sender, TreeViewEventArgs e)
{
var nodename = treeView1.Nodes.Find("*", true); //this line suppose to get clicked node name
var getdirs = Directory.GetDirectories(nodename); //error: It says nodename isnt string type
foreach (var getdir in getdirs)
{
treeView1.SelectedNode.Nodes.Add(getdir);
}
}
If you have any source, example or something simple like what im going to make, its a big help.
You can use this code to return Node Name:
protected void treeView1_AfterSelect (object sender,
System.Windows.Forms.TreeViewEventArgs e)
{
// Determine by checking the Text property.
MessageBox.Show(e.Node.Text);
}
I initially have a Fileupload tool to upload a textfile, manipulate its content and display into a Listbox or Textbox. The limitation however is Fileupload only supports single uploading, at least to the version of .Net Framework I am using.
What I intend to do is just use a button control and remove the Fileupload. Upon Button click I need to read the textfiles inside a designated folder path and display first the contents inside a multiple lined textbox. (not just the file name) This is my intially written codes, and it is not working.
protected void btnGetFiles_Click(object sender, EventArgs e)
{
string content = string.Empty;
DirectoryInfo dinfo = new DirectoryInfo(#"C:\samplePath");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
//ListBox1.Items.Add(file.Name);
content += content;
}
txtContent.Text = content;
}
Since your's is web based application you can't access physical paths like c:\\.. you should use Server.MapPath anyway(As per the comment, you don't need to get the file with Server.MapPath). Then for getting the content you can try something like the following:
protected void btnGetFiles_Click(object sender, EventArgs e)
{
try
{
StringBuilder content = new StringBuilder();
if (Directory.Exists(#"C:\samplePath"))
{
// Execute this if the directory exists
foreach (string file in Directory.GetFiles(#"C:\samplePath","*.txt"))
{
// Iterates through the files of type txt in the directories
content.Append(File.ReadAllText(file)); // gives you the conent
}
txtContent.Text = content.ToString();
}
}
catch
{
txtContent.Text = "Something went wrong";
}
}
you wrote content += content;, that is the problem. change it to content += file.Name;, it will work.
I've been having a problem with the following code:
namespace Viewer
{
public partial class Form1 : Form
{
int count = 0;
LinkLabel[] linkLabel = new LinkLabel[200];
string filename;
string extension;
string filepath;
private void btnLoad_Click(object sender, EventArgs e)
{
// Creates a Directory for the Movies Folder
DirectoryInfo myDirectory = new DirectoryInfo(#"C:\Users\User\Movies");
// Creates a list of "File info" objects
List<FileInfo> ls = new List<FileInfo>();
// Adds filetypes to the list
ls.AddRange(myDirectory.GetFiles("*.mp4"));
ls.AddRange(myDirectory.GetFiles("*.avi"));
// Orders the list by Name
List<FileInfo> orderedList = ls.OrderBy(x => x.Name).ToList();
// Loop through file list to act on each item
foreach (FileInfo filFile in orderedList)
{
// Creates a new link label
linkLabel[count] = new LinkLabel();
// Alters name info for display and file calling
filepath = filFile.FullName;
extension = filFile.Extension;
filename = filFile.Name.Remove(filFile.Name.Length - extension.Length);
// Write to the textbox for functional display
textBox1.AppendText(filename + "\r\n");
// Alters link label settings
linkLabel[count].Text = filename;
linkLabel[count].Links.Add(0, linkLabel[count].Text.ToString().Length, filepath);
linkLabel[count].LinkClicked += new LinkLabelLinkClickedEventHandler(LinkedLabelClicked);
// Adds link label to table display
tblDisplay.Controls.Add(linkLabel[count]);
// Indexes count up for arrays
count = count + 1;
}
}
private void LinkedLabelClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start(filepath);
}
}
}
My goal is to generate a table of links to all of the media files that I add at launch, and have the links open the files in their respective players.
As of right now, it generates all of the links properly, but whenever I click on any of them, it launches the last item in the list.
For example, if the list contains "300", "Gladiator", and "Top Gun", no matter which link I click, it opens "Top Gun".
I assume that this has to do with it calling the variable "filepath" in the click event, which is left in it's final state. However, I'm not exactly clear on how to create a static link value or action on each individual link, as all of the answers I've researched are in regards to single linklabel situations, not dynamic set-ups.
Any help/advice would be appreciated!
Try as below:
In foreach loop add one line more like:
linkLabel[count].Tag = filepath;
then in click event get this path as blow,
private void LinkedLabelClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string filepath = ((LinkLabel)sender).Tag.tostring();
System.Diagnostics.Process.Start(filepath);
}