How to Update an Excel Reader without using an openfiledialog C# - c#

I've probably worded the question wrongly but it is easier to explain.
Basically on my form I have a button where if you click it, it opens up an OpenFileDialog search box and you are able to open an excel file and it gets displayed on various datagridview boxes in the form. And then you can input data into the excel worksheets. However because i'm a novice programmer, I can only update those datagridview's by clicked the button again and going through the OpenFileDialog again.
Here is the code I use to initially read the excel worksheets.
private void button18_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel Workbook|*.xlsx", ValidateNames = true })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(fs);
reader.IsFirstRowAsColumnNames = true;
result = reader.AsDataSet();
cboSheet.Items.Clear();
cboSheet_mirror.Items.Clear();
resultSheet.Items.Clear();
foreach (System.Data.DataTable dt in result.Tables)
{
cboSheet.Items.Add(dt.TableName);
cboSheet_mirror.Items.Add(dt.TableName);
resultSheet.Items.Add(dt.TableName);
}
reader.Close();
}
(...)
The cboSheet and resultSheets aren't relevant they are just what I use to navigate the different worksheets.
What I want to do is create a method where it updates the datagridview's with the edited excel worksheet but without the user having to go through the OpenFileDialog process every time, the program just knows the path to the excel file.
Hopefully that makes sense.

The simplest approach to just remembering the file path would be to save it inside a class member after the user successfully selects a file:
string currentFilePath {get;set;} //Class member that will hold the path
private void button18_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel Workbook|*.xlsx", ValidateNames = true })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
this.currentFilePath = ofd.FullName; //remember the path here
(...)
Then in any other method or event handler inside your class you can read that path and open the excel file again without the need of another file selection process:
private void someOtherButton_Click(object sender, EventArgs e)
{
//read the file from the remembered path
FileStream fs = File.Open(this.currentFilePath, FileMode.Open, FileAccess.Read);
IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(fs);
(...)
For more information about this topic I'd recommend reading some articles (like this one) about Variable scopes

I think you should have a TextBox -e.g. ExcelFileTextBox- where you browse for your Excel file that after checking for DialogResult.OK set its Text property, This will also inform user about Excel path and filename.
You should move your Excel reading data to a - private - method instead, something like this:
private void ReadExcelData(string filename)
{
FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read);
IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(fs);
reader.IsFirstRowAsColumnNames = true;
result = reader.AsDataSet();
cboSheet.Items.Clear();
cboSheet_mirror.Items.Clear();
resultSheet.Items.Clear();
foreach (System.Data.DataTable dt in result.Tables)
{
cboSheet.Items.Add(dt.TableName);
cboSheet_mirror.Items.Add(dt.TableName);
resultSheet.Items.Add(dt.TableName);
}
reader.Close();
}
And your browse button code will become:
private void button18_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel Workbook|*.xlsx", ValidateNames = true })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
ExcelFileTextBox.Text = ofd.FileName;
ReadExcelData(ofd.FileName);
}
}
}
Then add a refresh button that it also calls ReadExcelData like this:
private void RefreshButton_Click(object sender, EventArgs e)
{
ReadExcelData(ExcelFileTextBox.Text);
}
HTH

Related

c# wpf only 1 file gets selected

I created a WPF app in which I want to select many files from any given directory. The problem is that whenever I try to select multiple files, it will just copy the first file exactly as many times as many files I selected, instead of giving me all the different files.
What am I doing wrong?
TextFile textFile = new TextFile();
string[] arrAllFiles;
private void btnOpenFiles_Click(object sender, RoutedEventArgs e)
{
Stream myStream;
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() ==true)
{
//string sFileName = choofdlog.FileName;
arrAllFiles = choofdlog.FileNames; //used when Multiselect = true
}
//add all files in textbox
for (var i = 0; i < arrAllFiles.Length; i++)
{
textFile.files.Add(choofdlog);
myStream = textFile.files[i].OpenFile();
StreamReader reader = new StreamReader(myStream);
textFile.readFile.Add(reader);
lbFiles.Items.Add(arrAllFiles[i]);
}
}
i only use c# occasionally, so i can't give you a syntactical guarantee, but what i see at first glance is this
textFile.files.Add(choofdlog);
should be
textFile.files.Add(arrAllFiles[i]);
or
textFile.files.Add(choofdlog[i]);

Writing Binary file at certain address

What I'm trying to do is read a blank file with no extension. From there, open the file and read it at a certain offset. Here's what I've done for that:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open 234cec File";
if (ofd.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(File.OpenRead(ofd.FileName));
BinaryReader br = new BinaryReader(File.OpenRead(ofd.FileName));
string Texture1 = null;
for (int i = 0x2D670DE; i <= 0x2D6712F; i++)
{
br.BaseStream.Position = i;
Texture1 += br.ReadChar().ToString();
}
br.Close();
textBox1.Text = Texture1;
}
else
{
MessageBox.Show("Error");
}
}
The program works just fine and displays text in a textbox from what it read.
However, I want to be able to write back in the file, from what's in the textbox it read, with a Save button.
i.e. from what I modify in the textbox, then have it save back to my file (at the specified address) WITHOUT changing the file size (like replacing what's there).
The file I'm reading is a kinda big file like 120MB and it doesn't just contain text, it also contains other hex/code and such.
My problem is, I'm clueless as to what line I should do for my Save button after I modify what it read in the Textbox. Any help?

Choose file C# and get directory

I'm trying to open a file dialog box so the user can choose the location of an access database. Can someone explain how to add a file dialog when a button is clicked and also how to transform the user choice into a string that contains the file directory ( c:\abc\dfg\1234.txt)?
Thanks
As you did not state the technology you use (WPF or WinForms), I assume you use WinForms. In that case, use an OpenFileDialog in your code. After the dialog was closed, you can get the selected full file name using the FileName property.
There is the following example of how to use it on the documentation page I linked above, which I modified slightly as you want the file name, not the stream:
private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\" ;
openFileDialog1.Filter = "Database files (*.mdb, *.accdb)|*.mdb;*.accdb" ;
openFileDialog1.FilterIndex = 0;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
string selectedFileName = openFileDialog1.FileName;
//...
}
}
Based on your previous question I assume you are using WinForms.
You can use the OpenFileDialog Class for this purpose. See the code below which will run on your button Click event assuming your button id is button1:
private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "Access files (*.accdb)|*.accdb|Old Access files (*.mdb)|*.mdb";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
var path = openFileDialog1.FileName;
}
}
More information.
Assuming that you actually have a form with button (button1)...
At the constructor hook into button1's click event
...
button1.Click += button1_Click;
...
Then define the handling function and use System.Windows.Forms.OpenFileDialog as you like.
void button1_Click(object sender, EventArgs e)
{
string oSelectedFile = "";
System.Windows.Forms.OpenFileDialog oDlg = new System.Windows.Forms.OpenFileDialog();
if (System.Windows.Forms.DialogResult.OK == oDlg.ShowDialog())
{
oSelectedFile = oDlg.FileName;
// Do whatever you want with oSelectedFile
}
}
It's actually fairly simple
namespace YourProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string path = "";
//Declare the File Dialog
OpenFileDialog ofd = new OpenFileDialog();
private void button1_click(object sender, EventArgs e)
{
if (odf.ShowDialog() == DialogResult.OK)
{
path = ofd.FileName;
}
}
}
}

OpenFileDialog C# Asking for opening twice?

I have used a Telerik Browse Editor to open a file on my program. But for some reason it is asking me for the file twice. From the code below can anyone see why?
private void radBrowseEditor1_ValueChanged(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Title = #"Open .HRM File";
openFileDialog.InitialDirectory = #"C:\Users\mike\Desktop";
openFileDialog.Filter = #"HRM files (*.hrm)|*.hrm|All files (*.*)|*.*";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
}
using (StreamReader reader = new StreamReader(openFileDialog.FileName, System.Text.Encoding.Default))
{
HRM.Active.Raw = reader.ReadToEnd();
}
}
}
Probably something really simple. Pretty sure that code I used when I had a toolstrip before I installed Telerik and it worked fine.
After reading this, http://www.telerik.com/help/winforms/editors-browse-editor-working-with.html, it seems like you don't even need to bother with the openFileDialog. It does look like you should check that the value is not blank.
private void radBrowseEditor1_ValueChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(radBrowseEditor1.Value.ToString()))
{
using (StreamReader reader = new StreamReader(radBrowseEditor1.Value.ToString(), System.Text.Encoding.Default))
{
HRM.Active.Raw = reader.ReadToEnd();
}
}
}

Convert DataTable to XML file and viceversa

I am having a problem with reading an XML file onto a DataTable. Initially, I am writing a Datatable to an XML file and saving it. Now, when I want to read the XML file back to the DataTable, it's not happening.
The following code is for writing the file:
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
if (myDT_For_DGV.Rows.Count != 0)
{
saveFileDialog1.ShowDialog();
saveFileDialog1.FileName = "checkOutFile.xml";
myDT_For_DGV.TableName = "CheckOutsAndIns";
myDT_For_DGV.WriteXml(saveFileDialog1.FileName, true);
}
else
{
MessageBox.Show("Please add licences to DataGridView, you havent added any licences as of now", "Alert");
}
}
And for reading the file:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
//write code to open file
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//myFile = openFileDialog1.FileName;
System.IO.MemoryStream xmlStream = new System.IO.MemoryStream();
xmlStream.Position = 0;
myDT_For_DGV.ReadXml(openFileDialog1.FileName);
//MessageBox.Show(openFileDialog1.FileName);
}
}
It might be easier to just work with the higher-level DataSet, like this:
DataSet dataSet = new DataSet();
DataTable dataTable = new DataTable();
dataSet.Tables.Add(dataTable);
// Save to disk
dataSet.WriteXml(#"C:\MyDataset.xml");
// Read from disk
dataSet.ReadXml(#"C:\MyDataset.xml");
I fixed it, The Problem is, the tablename was assigned while saving but not while reading. So assign the table name globally, which will let it read and write without any problem.
so the code will be,
myDT_For_DGV.TableName = "CheckOutsAndIns";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
myDT_For_DGV.ReadXml(#openFileDialog1.FileName);
//MessageBox.Show(openFileDialog1.FileName);
}
//TO WRITE TO XML
if (myDT_For_DGV.Rows.Count != 0)
{
saveFileDialog1.ShowDialog();
saveFileDialog1.FileName = "checkOutFile.xml";
myDT_For_DGV.WriteXml(saveFileDialog1.FileName, true);
}

Categories