I have an ASP:TreeView that I want to show on icon based upon the file extension. Here is my current code. I have also tried ondatabound using the same code but that does not work neither.
protected void MyTree_TreeNodeExpanded(object sender, TreeNodeEventArgs e)
{
string fileExt = Path.GetExtension(e.Node.Selected.ToString());
if (fileExt == ".pdf")
{
MyTree.LeafNodeStyle.ImageUrl = "/Images/icons/pdf_icon.png";
}
else
{
MyTree.LeafNodeStyle.ImageUrl = "/Images/icons/document_icon.png";
}
}
The script above does not loop through the file structure. In the example below, the pdf file should have the pdf icon and the rest have the document icon.
Server.MapPath specifies the relative or virtual path to map to a physical, but ImageUrl value must be absolute url or relative url.
You need to
Replace
MyTree.LeafNodeStyle.ImageUrl = Server.MapPath("~/Images/icons/pdf_icon.png");
with
MyTree.LeafNodeStyle.ImageUrl = "/Images/icons/pdf_icon.png";
Edit
-e.Node return the expanded Node that is "Nursing" node in your example, but you need to loop through e.Node.ChildNodes.
- e.Node.Selected Returns boolean value you should use e.Node.Text to get node text.
- MyTree.LeafNodeStyle.ImageUrl changes all leafs style in tree so you need to change ImageUrl for every leaf.
this code must do the job.
protected void MyTree_TreeNodeExpanded(object sender, TreeNodeEventArgs e)
{
for (int i = 0; i < e.Node.ChildNodes.Count; i++)
{
if (e.Node.ChildNodes[i].ChildNodes.Count != 0)
continue;
string fileExt = Path.GetExtension(e.Node.ChildNodes[i].Text);
if (fileExt == ".pdf")
{
e.Node.ChildNodes[i].ImageUrl = "/Images/icons/pdf_icon.png";
}
else
{
e.Node.ChildNodes[i].ImageUrl = "/Images/icons/document_icon.png";
}
}
}
Related
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!
Say I want listBox1 to contain a set of first names. And when someone clicks on one of those first names, it will display the last name in listBox2 and already selected.
I seem to not be able to have the second listbox have it already selected.
So if the first item in listBox1 is selected, the first item in listBox2 is selected. And so on.
How would such be possible?
Here is some code:
private void materialFlatButton3_Click_1(object sender, EventArgs e)
{
OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
OpenFileDialog1.Multiselect = true;
OpenFileDialog1.Filter = "DLL Files|*.dll";
OpenFileDialog1.Title = "Select a Dll File";
if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// put the selected result in the global variable
fullFileName = new List<String>(OpenFileDialog1.FileNames);
foreach (string s in OpenFileDialog1.FileNames)
{
listBox2.Items.Add(Path.GetFileName(s));
listBox4.Items.Add(s);
}
}
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string text = listBox2.GetItemText(listBox2.SelectedItem);
textBox3.Text = text;
}
In listbox4, it displays the full path. In listbox2, it displays just the name of the file.
How would I make it so when someone clicks on a file in listbox2, its corresponding path will be selected in listbox4?
Create you own type for storing and displaying the file names:
public class FileItem
{
public FileItem (string path) => FullPath = path;
public string FullPath { get; }
public override ToString() => Path.GetFileName(FullPath);
}
And add these items to the listbox. That way you can store the full path and display the file name at the same time.
Alternatively just keep a reference to the original Files array or copy its content to another array. Then get the full path from this array through the selected index instead of from a second listbox ony used to store things.
Create a class which represent full path and name for displaying.
Then use bind loaded data to the ListBox
public class MyPath
{
public string FullPath { get; private set; }
public string Name '
{
get { return Path.GetFileName(s) }
}
public MyPath(string path)
{
FullPath = path;
}
}
// Load and bind it to the ListBox
var data = OpenFileDialog1.FileNames
.Select(path => new MyPath(path))
.ToList();
// Name of the property which will be used for displaying text
listBox1.DisplayMember = "Name";
listBox1.DataSource = data;
private void ListBox1_SelectedValueChanged(object sender, EventArgs e)
{
var selectedPath = (MyPath)ListBox1.SelectedItem;
// Both name and full path can be accesses without second listbox
// selectedPath.FullPath
// selectedPath.Name
}
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.
Okay, so I'm working with some if/else statements now. But, I'm having some trouble.
Here's the full code that is depending on the version clicked.
private void button_Click(object sender, EventArgs e)
{
using (OpenFileDialog file = new OpenFileDialog())
{
file.Filter = "File(*.file)|*.jar|All Files (*.*)|*.*";
file.Title = "Open File...";
if (file.ShowDialog() == DialogResult.OK)
{
string fullFileName = item.FileName;
FileInfo userSelected = new FileInfo(fullFileName);
string fileNameWithExt = Path.GetFileName(fullFileName);
string destPath = Path.Combine(Application.UserAppDataPath, fileNameWithExt);
string mcAD = Environment.ExpandEnvironmentVariables("%AppData%");
File.Copy(item.FileName, mcAD, true);
}
}
But what I'm having trouble is with this.
Below is the code, but here's how the program is lain out.
There's a menu at the bottom of the program. It's named "Version" you click and you can choose version 1.0, 2.0, and 3.0. I have it set so there's text beside it telling it which version you chose.
Now, the issue is I need an if/else statement for all the version for the above code cause all files for each version go to a different location.
Here's the other code...
private void Version_1_0_Click(object sender, EventArgs e)
{
string Version_1_0_Selected = VersionText.Text = "1.0 Selected";
}
private void Version_1_6_1_Click(object sender, EventArgs e)
{
string Version_2_0_Selected = VersionText.Text = "2.0 Selected";
}
private void Version_3_0_Click(object sender, EventArgs e)
{
string Version_3_0_Selected = VersionText.Text = "3.0 Selected";
}
You can use Control.Tag for storing version index. For example:
private void Version_1_0_Click(object sender, EventArgs e)
{
VersionText.Text = "1.0 Selected";
VersionText.Tag= 1;
}
Then, you can define your target paths:
string[] paths = {#"c:\path1.txt", #"c:\path2.txt", #"c:\path3.txt"};
Finally, when you writing your files you can lookup the path like this:
File.Copy(item.FileName, paths[VersionText.Tag], true);
You might need to modify this code if the target file name is based on the source file name, but that should not be difficult.
Abstract the FileDialog code to a separate method and pass in your version string so that you can then perform the checks.
public void OpenVersionDialog(string version)
{
string mcAD = GetCopyPath(version);
if(!String.IsNullOrEmpty(mcAD))
{
using (OpenFileDialog file = new OpenFileDialog())
{
file.Filter = "File(*.file)|*.jar|All Files (*.*)|*.*";
file.Title = "Open File...";
if (file.ShowDialog() == DialogResult.OK)
{
string fullFileName = item.FileName;
FileInfo userSelected = new FileInfo(fullFileName);
string fileNameWithExt = Path.GetFileName(fullFileName);
string destPath = Path.Combine(Application.UserAppDataPath, fileNameWithExt);
File.Copy(item.FileName, mcAD, true);
}
}
}
else
{
//invalid version selected
}
}
public string GetCopyPath(string versionInput)
{
//these are case-insensitive checks but you can change that if you want case-sensitive
if(string.Equals(versionInput, "1.0 Selected", StringComparison.OrdinalIgnoreCase))
return "YOUR_PATH_FOR 1.0";
if(string.Equals(versionInput, "2.0 Selected", StringComparison.OrdinalIgnoreCase))
return "YOUR_PATH_FOR 2.0";
if(string.Equals(versionInput, "3.0 Selected", StringComparison.OrdinalIgnoreCase))
return "YOUR_PATH_FOR 3.0";
return String.Empty;
}
If I understand correctly that should be what you want. If you have more versions, you could store them in a dictionary where the key is the version and the value is the path that the file should be copied to.
I'm not sure what the difference between mcAD and destPath is but I assume mcAD is the variable that changes based on the version as that's being used in File.Copy.
I assign values from a queryString to these textboxes and that works fine , but whenever I edit the text in one of them and try to get the edited data to be saved in XML node, I can't
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString != null)
{
TextBox_firstname.Text = Request.QueryString["column1"];
TextBox_lastname.Text = Request.QueryString["column2"];
}
else
{
}
}
Is there something with this code? It saves the unedited version in the nodes!
public string str_id;
public int id;
id = int.Parse(str_id);
XDocument xdoc = XDocument.Load(filepath);
if (id == 1)
{
var StudentNodeWithID1 = xdoc.Descendants("students")
.Elements("student")
.Where(s => s.Element("id").Value == "1")
.SingleOrDefault();
StudentNodeWithID1.Element("first_name").Value = TextBox_firstname.Text;
StudentNodeWithID1.Element("last_name").Value = TextBox_lastname.Text;
}
Page_Load is fired on every load (on postback as well as on initial load). Your code is currently defaulting those values from Request.QueryString on every load, before your event handler tries to save it.
Do this instead:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && Request.QueryString != null)
{
TextBox_firstname.Text = Request.QueryString["column1"];
TextBox_lastname.Text = Request.QueryString["column2"];
}
else
{
}
}
If you are submitting the edited textboxes, then you will need to wrap the code in your Pageload with IsPostback check to ensure that values do not get reset to their originals.