I have point files like:
I have created code that allows users to select the files from a dialog box and it will populate the data to the gridview.
private void cmdload_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("Point");
table.Columns.Add("X");
table.Columns.Add("Y");
table.Columns.Add("Z");
table.Columns.Add("R");
table.Columns.Add("A");
table.Columns.Add("B");
table.Columns.Add("C");
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "C:\\";
openFileDialog1.Filter = "Data Files (*.PNT)|*.PNT";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
string filename = openFileDialog1.FileName;
using (var reader = File.OpenText(filename))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(' ');
table.Rows.Add(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7]);
}
dataGridView1.DataSource = table;
}
}
}
}
catch (Exception ex) // you need to add the catch block if yo are using try block
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
This code works fine, however the datagridview does not display the value.
If you are not creating the DataGridView columns through code then you have to set the DataPropertyName of the DataGridViewColumn to the columns ids in the DataTable.
Sample code:
dataGridView1.AutoGenerateColumns = false;
DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn();
col1.Name = "Point";
col1.HeaderText = "Point";
col1.DataPropertyName = "Point";
dataGridView1.Columns.Add(col1)
The other way is to set AutoGenerateColumns property to true to create the required columns automatically and bind the data to the DataTable. By this you don't have to create columns through code like in the above sample code.
dataGridView1.AutoGenerateColumns = true;
Related
Im working on some small WPF project, with user inputs, three for strings and one for checkbox.
When the user has filled every input the information will save as an xml file.
When i try to load the informations back into the input fields, it works with the strings but not the checkbox. Every file i load, the checkbox is always unchecked.
What am i missing ?
This is how i save the information.
private void savebtn_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "CompressorTypeList";
dlg.DefaultExt = ".xml";
dlg.Filter = "XML documents (.xml)|*.xml";
Nullable<bool> result = dlg.ShowDialog();
string filename = dlg.FileName;
Information info = new Information();
info.StudentName = txtbox1.Text;
info.StudentID = txtbox2.Text;
info.StudentPassword = txtbox3.Password;
info.BoolDataValue = (bool)ckbox.IsChecked;
SaveXml.savedata(info, filename);
txtbox1.Text = null;
txtbox2.Text = null;
txtbox3.Password = null;
ckbox.IsChecked = false;
}
And this is how i load the informations back.
private void PopulateXMLData()
{
try
{
var openFile = new OpenFileDialog();
openFile.Filter = "XML documents (.xml)|*.xml";
Nullable<bool> result = openFile.ShowDialog();
string XMLFilePath = openFile.FileName;
DataSet ds = new DataSet();
ds.ReadXml(XMLFilePath);
foreach (DataRow dr in ds.Tables[0].Rows)
{
txtbox1.Text = dr["StudentName"].ToString().Trim();
txtbox2.Text = dr["StudentID"].ToString().Trim();
txtbox3.Password = dr["StudentPassword"].ToString().Trim();
ckbox.IsChecked = (bool)dr["BoolDataValue"];
}
}
catch (Exception)
{
MessageBox.Show("Load error");
}
}
Goal:
Show cell value as just the filename, not full path
Selected cell value, open folder where file is located on click
Current Code to load data grid view:
private void Form14_Load(object sender, EventArgs e)
{
int select = Convert.ToInt32(f9.dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
// MySQL connection string
using (var conn = new MySqlConnection(ConnectionString()))
{
using (var mySqlDataAdapter = new MySqlDataAdapter(#"select file_attachment1, file_attachment2,file_attachment3,file_attachment4,file_attachment5,file_attachment6,file_attachment7,file_attachment8,file_attachment9,file_attachment10 from document_control where id = " + select + "", conn))
{
using (var dataSet = new DataSet())
{
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
dataGridView1.Columns[0].HeaderText = "Old File 1";
dataGridView1.Columns[1].HeaderText = "Old File 2";
dataGridView1.Columns[2].HeaderText = "Old File 3";
dataGridView1.Columns[3].HeaderText = "Old File 4";
dataGridView1.Columns[4].HeaderText = "Old File 5";
dataGridView1.Columns[5].HeaderText = "Old File 6";
dataGridView1.Columns[6].HeaderText = "Old File 7";
dataGridView1.Columns[7].HeaderText = "Old File 8";
dataGridView1.Columns[8].HeaderText = "Old File 9";
dataGridView1.Columns[9].HeaderText = "Old File 10";
}
}
}
}
Output:
Code to open the directory:
private void button1_Click(object sender, EventArgs e)
{
if (this.dataGridView1.CurrentCell != null)
{
Cursor.Current = Cursors.WaitCursor;
int select = Convert.ToInt32(f9.dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
string file = dataGridView1.CurrentCell.Value.ToString();
Cursor.Current = Cursors.Default;
if (File.Exists(file))
{
Cursor.Current = Cursors.WaitCursor;
Process.Start("explorer.exe", " /select, " + file);
Cursor.Current = Cursors.Default;
}
else
{
MessageBox.Show("No File Found...");
}
}
else
{
MessageBox.Show("No record selected");
}
}
Desired Output:
Instead of cells to show the full path, show just the filename, Like so: test.csv.
On button click, open the file location of full path.
What I have tried:
Have already altered mysqlDataAdapter query to use substring_index to get the filename, which achieves my first goal.
But, if I click button1 file is non existent.. because it is not looking for full path.
Question:
What is a good method to achieve these 2 goals?
Currently struggling to understand, how I can display cells as filename. But in the background represent it as a full value. Where user will be able to open the full path name.
One way is that you get the name of the file in C # code and at the same time save the address in the cell property:
Current Code to Load DGV:
private void Form14_Load(object sender, EventArgs e)
{
// You previus code here ...
// Here is you new modify code:
using (var dataSet = new DataSet())
{
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
for(int colidx=0; colidx<dataGridView1.Columns.Count; colidx++) // You have index from 0 to 9
{
// if you use C# 7 you use:
// dataGridView1.Columns[colidx].HeaderText = $"Old File {(colidx+ 1).ToString()};
dataGridView1.Columns[colidx].HeaderText = "Old File " + (colidx+ 1).ToString();
// The magic:
for(int rowidx = 0; rowidx < dataGridView1.Rows.Count; rowidx++)
{
string filepathcell = dataGridView1.Rows[rowidx].Cells[colidx].Value.ToString();
// Only filename, remember: implements "using System.IO;" and this may launch exception, be careful
dataGridView1.Rows[rowidx].Cells[colidx].Value = Path.GetFileName(filepathcell);
// Save full pathfile:
dataGridView1.Rows[rowidx].Cells[colidx].Tag = filepathcell;
}
}
}
}
And this is your modify code to open directory:
Open Dir
private void button1_Click(object sender, EventArgs e)
{
if (this.dataGridView1.CurrentCell != null)
{
Cursor.Current = Cursors.WaitCursor;
// This is the only line modified
string file = dataGridView1.CurrentCell.Tag.ToString();
Cursor.Current = Cursors.Default;
if (File.Exists(file))
{
Cursor.Current = Cursors.WaitCursor;
Process.Start("explorer.exe", " /select, " + file);
Cursor.Current = Cursors.Default;
}
else
{
MessageBox.Show("No File Found...");
}
}
else
{
MessageBox.Show("No record selected");
}
}
I have a listbox which i can fill trough openfiledialog, which works but not the way i want it. I need 2 columns in my listbox 1 for the filepath and 1 for the fileName next to each other.
also i have another button which inserts all fileNames into the database, which works also but i also need the second column to update the path column in my database
Ive tried to make 2 columns 1 for the filename and 1 for the filepath, unfortunately i could only make 1 column work for my filename.
This is the code for filling in the listbox
private void btnOpenFiles_Click(object sender, RoutedEventArgs e)
{
lbfiles.Items.Clear();
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = true;
openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (openFileDialog.ShowDialog() == true)
{
foreach (string filename in openFileDialog.FileNames)
lbfiles.Items.Add(System.IO.Path.GetFileName(filename));
}
}
this is the code for inserting into the database
private void BtnToDatabase_Click(object sender, RoutedEventArgs e)
{
bool dupe = false;
foreach (String string2 in lbfiles.Items.Cast<String>().ToList())
{
{
string cat1 = string2.Substring(0, string2.Length);
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
String query = "INSERT INTO tblBestanden2 (BestandNaam,toegewezen,Username,Status) VALUES (#BestandNaam, #toegewezen, #username, #Status)";
using (SqlCommand command = new SqlCommand(query, sqlCon))
{
command.Parameters.AddWithValue("#BestandNaam", cat1);
command.Parameters.AddWithValue("#toegewezen", "1");
command.Parameters.AddWithValue("#username", "");
command.Parameters.AddWithValue("#Status", "0");
sqlCon.Open();
int result = command.ExecuteNonQuery();
if (!dupe)
{
if (result == 0)
{
sqlCon.Close();
MessageBox.Show("error");
}
else
{
sqlCon.Close();
MessageBox.Show("toegevoegd");
}
dupe = true;
}
}
}
}
}
}
If there is any confusion about my question please tell me and i will try my best to elaborate
Create a class with two properties:
public class File
{
public string Name { get; set; }
public string Path { get; set; }
}
And instances of this one to the ListBox:
private void btnOpenFiles_Click(object sender, RoutedEventArgs e)
{
lbfiles.Items.Clear();
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = true;
openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (openFileDialog.ShowDialog() == true)
{
foreach (string filename in openFileDialog.FileNames)
lbfiles.Items.Add(new File() { Name = System.IO.Path.GetFileName(filename), Path = filename });
}
}
You would then get the values by casting the items to File objects in your BtnToDatabase_Click event handler:
private void BtnToDatabase_Click(object sender, RoutedEventArgs e)
{
bool dupe = false;
foreach (File file in lbfiles.Items.OfType<File>())
{
string name = file.Name;
string path = file.Path;
...
}
}
In foreach statement, filepath is not included when this condition openFileDialog.ShowDialog() gets true, you are getting only filename. To get filepath, use System.IO.Path.GetFullPath(FileName);, you could get filepath for the filename
I got finally, how to download the file using the path. But I was wondering how can I keep the file name only on the grid view. While I need the full path for downloading.
On debugging I came to see that I cannot keep file name only on file upload. Since it is carried to the downloading section. If I keep file name, then file name is carried to the downloading part and the file is not downloaded.
Can anyone help me
Codes
private void UploadAttachment(DataGridViewCell dgvCell)
{
using (OpenFileDialog fileDialog = new OpenFileDialog())
{
//Set File dialog properties
fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Filter = "All Files|*.*";
fileDialog.Title = "Select a file";
fileDialog.Multiselect = true;
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string strfilename = fileDialog.FileName;
cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value = strfilename;
}
}
}
/// <summary>
/// Download Attachment from the provided DataGridViewCell
/// </summary>
/// <param name="dgvCell"></param>
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string fileName = Convert.ToString(dgvCell.Value);
if (!string.IsNullOrEmpty(fileName))
{
byte[] objData;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string s = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
objData = File.ReadAllBytes(s);
File.WriteAllBytes(saveFileDialog1.FileName, objData);
}
}
}
}
}
Your question is not clear. But if i get you right. Why don't you use use a column for the name and a hidden/0 width column for the file path. Its a grid and therefore you may have many columns. Plus i am thinking the code below should return the full path , unless you trim and can't see where you trim .
string strfilename = fileDialog.FileName;
To get the file name only you can use the Path
string filenameOnly= System.IO.Path.GetFileName(strfilename);
The above should return your file name only you can check here for better understanding.
Add another column and set the width to 0 . Example below
DataGridViewColumn column = dataGridView.Columns[0];
column.Width = 0;
cncInfoDataGridView.Columns.Add(column);
Save your file path in the new column width a 0 width and retrieve during download.
A similar question was asked here.
How to extract file name from file path name?
Dictionary<int, byte[]> _myAttachments;
private void btnUpload_Click(object sender, EventArgs e)
{
try
{
//Throw error if attachment cell is not selected.
//make sure user select only single cell
if (dataGridView1.SelectedCells.Count == 1 && dataGridView1.SelectedCells[0].ColumnIndex == 1)
{
UploadAttachment(dataGridView1.SelectedCells[0]);
}
else
MessageBox.Show("Select a single cell from Attachment column", "Error uploading file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error uploading file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnDownload_Click(object sender, EventArgs e)
{
//Throw error if attachment cell is not selected.
//make sure user select only single cell
//and the cell have a value in it
if (dataGridView1.SelectedCells.Count == 1 && dataGridView1.SelectedCells[0].ColumnIndex == 1 && dataGridView1.SelectedCells[0].Value != null)
{
DownloadAttachment(dataGridView1.SelectedCells[0]);
}
else
MessageBox.Show("Select a single cell from Attachment column", "Error uploading file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
//Throw error if attachment cell is not selected.
//make sure user select only single cell
//and the cell have a value in it
if (dataGridView1.SelectedCells.Count == 1 && dataGridView1.SelectedCells[0].ColumnIndex == 1 && dataGridView1.SelectedCells[0].Value != null)
{
DownloadAttachment(dataGridView1.SelectedCells[0]);
}
else
MessageBox.Show("Select a single cell from Attachment column", "Error uploading file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void UploadAttachment(DataGridViewCell dgvCell)
{
using (OpenFileDialog fileDialog = new OpenFileDialog())
{
//Set File dialog properties
fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Filter = "All Files|*.*";
fileDialog.Title = "Select a file";
fileDialog.Multiselect = false;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
FileInfo fileInfo = new FileInfo(fileDialog.FileName);
byte[] binaryData = File.ReadAllBytes(fileDialog.FileName);
dataGridView1.Rows[dgvCell.RowIndex].Cells[1].Value = fileInfo.Name;
if (_myAttachments.ContainsKey(dgvCell.RowIndex))
_myAttachments[dgvCell.RowIndex] = binaryData;
else
_myAttachments.Add(dgvCell.RowIndex, binaryData);
}
}
}
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string fileName = Convert.ToString(dgvCell.Value);
//Return if the cell is empty
if (fileName == string.Empty)
return;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
byte[] byteData = null;
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
byteData = _myAttachments[dgvCell.RowIndex];
File.WriteAllBytes(saveFileDialog1.FileName, byteData);
}
}
}
i have application with Listbox and files, each time i press on Add button the default C drive open and i want the application to remember the last path i used
private void btnAdd_Click(object sender, EventArgs e)
{
System.IO.Stream myStream;
OpenFileDialog thisDialog = new OpenFileDialog();
thisDialog.InitialDirectory = "c:\\";
thisDialog.Filter = "(*.snoop, *.pcap, *.cap, *.net)|*.snoop; *.pcap; *.cap; *.net|" + "All files (*.*)|*.*";
thisDialog.FilterIndex = 1;
thisDialog.RestoreDirectory = false;
thisDialog.Multiselect = true; // Allow the user to select multiple files
thisDialog.Title = "Please Select Source File";
thisDialog.FileName = lastPath;
List<string> list = new List<string>();
if (thisDialog.ShowDialog() == DialogResult.OK)
{
foreach (String file in thisDialog.FileNames)
{
try
{
if ((myStream = thisDialog.OpenFile()) != null)
{
using (myStream)
{
listBoxFiles.Items.Add(file);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
}
Save the last directory used in a global variable like this:
private string _lastPath = string.Empty;
then after the file selection initialize it:
if(thisDialog.Filenames.Length > 0)
_lastPath = Path.GetDirectoryName(thisDialog.Filenames[0]);
when you reopen the dialog set the InitialDirectory with this check:
thisDialog.InitialDirectory = (_lastPath.Length > 0 ? _lastPath: "c:\\");
and remove the thisDialog.FileName = lastPath;
EDIT --- UPDATE OF YOUR CODE ---
// This at the global level of your form
private string _lastPath = string.Empty;**
private void btnAdd_Click(object sender, EventArgs e)
{
System.IO.Stream myStream;
OpenFileDialog thisDialog = new OpenFileDialog();
thisDialog.InitialDirectory = (_lastPath.Length > 0 ? _lastPath: "c:\\");
thisDialog.Filter = "(*.snoop, *.pcap, *.cap, *.net)|*.snoop; *.pcap; *.cap; *.net|" + "All files (*.*)|*.*";
thisDialog.FilterIndex = 1;
thisDialog.RestoreDirectory = false;
thisDialog.Multiselect = true; // Allow the user to select multiple files
thisDialog.Title = "Please Select Source File";
thisDialog.FileName = lastPath;
List<string> list = new List<string>();
if (thisDialog.ShowDialog() == DialogResult.OK)
{
if(thisDialog.Filenames.Length > 0)
_lastPath = Path.GetDirectoryName(thisDialog.Filenames[0]);
foreach (String file in thisDialog.FileNames)
{
try
{
if ((myStream = thisDialog.OpenFile()) != null)
{
using (myStream)
{
listBoxFiles.Items.Add(file);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
}
You can use a Visual Studio have the last path value for every execution of the application.
Only have to go to Project Properties->Configuration and add a value descriptor.
Example:
Name = LastPath; Type = string; Scope = User; Value = "Default path";
And then after you rebuild yout application, you can set this property this way:
Settings.Default.LastPath = LastPathSelected;
later, you can retrieve the value with:
thisDialog.InitialDirectory = Settings.Default.LastPath;
thisDialog.InitialDirectory = Path.GetDirectoryName(lastPath);
Yes, you can use the OpenFileDialog.InitialDirectory property. Note: you are setting the directory and not the file. So be sure to remove the filename from the path.
more info here
remove this line and you have the last path
thisDialog.InitialDirectory = "c:\\";