Click here to Skip to main content
15,901,426 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I have written below code for getting files in the datagridview , but i am getting the whole path in the datagridview, but i need only the filename in the datagridview.
i am getting below path in datagridview.
C:\Program Files\Common Files\file.txt/pre>I require only file.txt in Datagrid view

What I have tried:

<pre>private void FillGridView()
		{
			try {
				if (System.IO.Directory.Exists(SelectedPath)) {
				String[] files = System.IO.Directory.GetFiles(SelectedPath);
					DataGridViewCheckBoxColumn CheckBoxColumn = new DataGridViewCheckBoxColumn();
					DataGridViewTextBoxColumn FileNameColumn = new DataGridViewTextBoxColumn();                
					CheckBoxColumn.HeaderText = "Check Items";
					FileNameColumn.HeaderText = "File Name";                
					dataGridView1.Columns.Clear();
					dataGridView1.Rows.Clear();               
					dataGridView1.Columns.Add(CheckBoxColumn);
					dataGridView1.Columns.Add(FileNameColumn);   
					dataGridView1.Columns[1].ReadOnly = true;				  				            
					for (int i = 0; i < files.Length; i++) {
				   
					   dataGridView1.Rows.Add(false, files[i]);
					}     									
				}					
			} catch (Exception e) {
				MessageBox.Show(e.Message);
			}
		}
Posted
Updated 28-May-18 23:28pm

1 solution

you can use Path.GetFileName(SelectedPath); to get the file name.

Click for more detail...[^]
 
Share this answer
 
Comments
Member 13846964 29-May-18 5:31am    
@JAcob i have already tried doing that but i am getting the fullpath, instead of file name in the datagridview row.
Jinto Jacob 29-May-18 5:58am    
you are using
String[] files = System.IO.Directory.GetFiles(SelectedPath);
which gives full path and adding the same path to grid

dataGridView1.Rows.Add(false, files[i]);

try to use something like

dataGridView1.Rows.Add(false,Path.GetFileName( files[i]));
Member 13846964 29-May-18 6:32am    
@Jacob, thanks for solving, i am using this outside the loop and trying, it worked now, thanks a lot..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900