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);
}
Related
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
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?
currently I able to import an excel file into gridview by using exceldatareader library. Now, I want to further improve to import multiple excel sheet into gridview. This is the output I wish to do. ImageOutput
I able to get the excel sheet name into the dropdownlist but I have no idea how to get the data from the second sheet. I tried google but still cant found any answer yet.
So now my problem how can I select the sheet name from the dropdownlist and show that sheet data in the gridview.
Below is my code:
public partial class ReadExcel : System.Web.UI.Page
{
DataSet result;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLoad_Click(object sender, EventArgs e)
{
dataUpload();
}
protected void dataUpload()
{
if (FileUpload1.HasFile)
{
string path = Path.GetFileName(FileUpload1.PostedFile.FileName);
string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string filepath = Server.MapPath("~/" + path);
FileUpload1.SaveAs(filepath);
FileStream stream = File.Open(filepath, FileMode.Open, FileAccess.Read);
//for excel 2003
// IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
// for Excel 2007
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
excelReader.IsFirstRowAsColumnNames = true;
result = excelReader.AsDataSet();
ddlSheet.Items.Clear();
foreach(DataTable dt in result.Tables)
{
ddlSheet.Items.Add(dt.TableName);
}
//excelReader.IsFirstRowAsColumnNames = true;
while (excelReader.Read())
{
// int i = excelReader.GetInt32(0);
GridView1.DataSource = result;
GridView1.DataBind();
}
}
else
{
lblError.Text = "Unable to upload the selected file. Please check the selected file path or confirm that the file is not blank!";
}
}
protected void ddlSheet_SelectedIndexChanged(object sender, EventArgs e)
{
GridView1.DataSource = result;
GridView1.DataBind();
}
}
Hummm, interesting. I've never tried what you described here, but I think the link below will help you get started.
https://msdn.microsoft.com/en-us/library/aa480727.aspx?f=255&MSPPError=-2147217396
Also, below is a small sample of code to get things going.
You can use the excel library from this link http://code.google.com/p/excellibrary/. There is actually an example code provided on this page, it demonstrates how to read from an excel file.
using ExcelLibrary.SpreadSheet;
// open xls file
Workbook book = Workbook.Load(file);
Worksheet sheet = book.Worksheets[0];
// iterate with a proper condition, at the moment it will iterate with a given length!
for (int i = 0; i < length; i++)
{
comboBox.Items.Add(sheet.Cells[i,column_index].Value);
}
Your result is a DataSet object that has Tables[] property and ExcelDataReader stores each sheet as a table.
So, I think you should change
GridView1.DataSource = result;
to
GridView1.DataSource = result.Tables[ddlSheet.SelectedText];
I have a listbox that displays the names of the files that are opened either with a dragDrop functionality or with an OpenFileDialog, the file paths are stored in the List named playlist, and the listbox only displays the names without paths and extensions. When my form closes, the playlist content is saved to a .txt file. When I open again my application, the content in the text file is stored again in the listbox and the playlist. But when I add new files after re-opening the form, I don't know why it leaves a blank line between the last files and the recently added ones.
This is the code I use to WRITE the content of playlist(List) in the txt file:
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if(listBox1.Items.Count > 0)
{
StreamWriter str = new StreamWriter(Application.StartupPath + "/Text.txt");
foreach (String s in playlist)
{
str.WriteLine(s);
}
str.Close();
}
This is the code used to READ the same txt file:
private void Form1_Load(object sender, EventArgs e) //Form Load!!!
{
FileInfo info = new FileInfo(Application.StartupPath + "/Text.txt");
if(info.Exists)
{
if (info.Length > 0)
{
System.IO.StreamReader reader = new System.IO.StreamReader(Application.StartupPath + "/Text.txt"); //StreamREADER
try
{
do
{
string currentRead = reader.ReadLine();
playlist.Add(currentRead);
listBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(currentRead));
} while (true);
}
catch (Exception)
{
reader.Close();
listBox1.SelectedIndex = 0;
}
}
else
{
File.Delete(Application.StartupPath + "/Text.txt");
}
}
else
{
return;
}
}
The code used to add files to listbox and playlist:
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select File(s)";
ofd.Filter = "Audio Files (*.mp3, *.wav, *.wma)|*.mp3|*.wav|*.wma";
ofd.InitialDirectory = "C:/";
ofd.RestoreDirectory = false;
ofd.Multiselect = true;
ofd.ShowDialog();
foreach (string s in ofd.FileNames)
{
listBox1.Items.Add(Path.GetFileNameWithoutExtension(s));
playlist.Add(s);
}
listBox1.SelectedIndex = 0;
This is what I get when I add new files after re-opening my form:
Thanks in advance, I hope StackOverflow community can help me!
First of all: debug your code and you'll find the problem yourself :)
Issue is the use of the WriteLine method. The last line you write should use the Write method instead so that you don't have an empty line at the end. Alternatively and easier to implement is to only add non-empty lines to your playlist such like this:
// ...
do
{
string currentRead = reader.ReadLine();
if (!string.IsNullOrWhiteSpace(currentRead)) // ignore empty lines
{
playlist.Add(currentRead);
listBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(currentRead));
}
} while (true);
As a side comment: while (true) and using exception handling is a bad approach to end a loop.
I am making a WPF program, and right now I want to be able to open and merge files. I have a button to open a file and I have a button to merge the file, and when I don't implement the "onTextChanged" method both buttons work properly and the files are formatted properly. But if I implement the onTextChanged method and use the merge file button, the previous 'file' gets extra lines in its output.
Open Button Code:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
//Open windows explorer to find file
OpenFileDialog ofd = new OpenFileDialog();
ofd.CheckFileExists = true;
if (ofd.ShowDialog() ?? false)
{
//clears the buffer to open new file
buffer.Clear();
//string to hold line from file
string text;
// Read the file and add it line by line to buffer.
System.IO.StreamReader file =
new System.IO.StreamReader(ofd.FileName);
while ((text = file.ReadLine()) != null)
{
buffer.Add(text);
}
//close the open file
file.Close();
//write each element of buffer as a line in a temporary file
File.WriteAllLines("temp", buffer);
//open that temporary file
myEdit.Load("temp");
}
}
Merge Button Code:
private void merge_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.CheckFileExists = true;
if (ofd.ShowDialog() ?? false)
{
string text;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(ofd.FileName);
while ((text = file.ReadLine()) != null)
{
buffer.Add(text); // myEdit.AppendText(text);
}
file.Close();
File.WriteAllLines("temp", buffer);
myEdit.Load("temp");
}
}
And when I execute this code, it adds lines in between the last 'file's output:
private void myEdit_TextChanged(object sender, EventArgs e)
{
tCheck.Stop();
tCheck.Start();
}
private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
tCheck.Stop();
Application.Current.Dispatcher.Invoke(new Action(() =>
{
buffer.Clear();
StringBuilder sb = new StringBuilder();
// pulls text from textbox
string bigS = myEdit.Text;
// getText();
for (int i = 0; i < (bigS.Length - 1); i++)
{
if (bigS[i] != '\r' && bigS[i + 1] != '\n')
{
sb.Append(bigS[i]);
}
else
{
buffer.Add(sb.ToString());
sb.Clear();
}
}
}));
}
If you are wondering why I don't use the Split method of a string, it is because I need to open 50+ MB text files and I get an out of memory exception upon using it. I really just want to keep formatting the same when I merge a file.
Wow this is a one line fix.
Original Line of Code:
buffer.Add(sb.ToString());
Changed (Correct) Line of Code:
buffer.Add(sb.ToString().Trim());
The changed worked, however if someone has any idea where these extra lines are coming from that would be helpful.