load text file and populate into the gridview - c#

I have a code that let user select the files and load the data in the text files to datagridview.
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 = "\\Yamaha";
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;
}
}
}
}
EDITED:
I have edited my code as suggested but the value just doesn't display. Please advise.
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);
}
}
}
The text file looks like :
I want the data files to be paste in the gridview when user load the files.
Now i not sure why my code doesnt work. Can anyone give me an advise please?

please have a look :
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:\\"; // your directory is also not defined properly
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";// have a look to filter as well
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)) // you need not to use '#filename' instead use just '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
{
}
}
hope it helps.

Related

C# - Add rows to a existing dataGridView using a textdocument

I'm currently adding data to my dataGridView1 using the Form1_Load load event. Now I'm trying to add more data from a textfile which im loading into the winforms application.
As you guys will see, I'm trying to add more rows into the dataGridView1 but those new rows wont be added. What am I doing wrong?
I appreciate any kind of suggestions and help.
getTexFilePath function code:
private void getTexFilePath()
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = #"C:\";
openFileDialog1.Title = "Browse Text Files";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.DefaultExt = "txt";
openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.ReadOnlyChecked = true;
openFileDialog1.ShowReadOnly = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
filePath = openFileDialog1.FileName;
foreach (var line in File.ReadAllLines(filePath))
{
var index = dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells["Column1"].Value = line;
dataGridView1.Rows[index].Cells["Column2"].Value = "undefined";
}
}
}
Form1_Load code:
private void Form1_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("Username", typeof(string));
table.Columns.Add("Links");
table.Rows.Add("No File uploaded", "Missing data");
dataGridView1.DataSource = table;
}
Not knowing all of your requirements, this would be where I'd start.
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
namespace DatagridView_AddRowsAfterInitialLoad_45922121
{
public partial class Form1 : Form
{
string filePath = "";
BindingList<dgventry> dgvSourceList = new BindingList<dgventry>();
public Form1()
{
InitializeComponent();
InitializeDGV();
//put initial values in the grid
dgvSourceList.Add(new dgventry { field1 = "yeah", field2 = "yeah in f2", field3 = "yeah in F3" });
//put values from the datafile
getTexFilePath();
}
private void InitializeDGV()
{
dataGridView1.DataSource = dgvSourceList;
}
private void getTexFilePath()
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = #"C:\";
openFileDialog1.Title = "Browse Text Files";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.DefaultExt = "txt";
openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.ReadOnlyChecked = true;
openFileDialog1.ShowReadOnly = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
filePath = openFileDialog1.FileName;
foreach (var line in File.ReadAllLines(filePath))
{
dgvSourceList.Add(new dgventry { field1 = line, field2 = "", field3 = "" });
}
}
}
}
public class dgventry
{
public string field1 { get; set; }
public string field2 { get; set; }
public string field3 { get; set; }
}
}
In Form1_Load you use a data source (DataTable instance) so your grid is data bound (means, the grid reflects the content of its source).
However, in getTexFilePath you just try to add rows to the grid itself in an unbound manner.
Solution 1
You should add new lines to your underlying DataTable instead.
Solution 2
Create a new table and reset the binding:
dataGridView1.DataSource = null;
DataTable newDataTable = ReadFileAsDataTable(fileName); // implement this
dataGridView1.DataSource = newDataTable;
Solution 3
Use a non-bound grid also in Load event, similarly to your getTexFilePath. But this is not recommended because in this case you do not have a clean UI independent model object (data source), and you can read business data only from the UI control, which is nasty.
The easy way to deal with this is to have your DataTable table as a member of your form class. So in Form_Load you just have:
table = new DataTable();
Then in your foreach loop in GetTexFilePath use the following:
DataRow dR = table.NewRow();
dR[0] = line;
dR[1] = "undefined";
table.rows.Add(dR);

C# - Find and convert Image path to base64

I'm working on an assignment and I'm trying to either convert an image to base64 but after trying some examples on here I get an error message saying the bytes can't exceed infinity, and someone in class suggested I should export the image path instead.
below is the code I have to open the image
private void button1_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "PNG Files (.png)|*.png|JPEG Files (.jpg)|*.jpg";
openFileDialog1.FilterIndex = 2;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Bitmap loadedImage = new Bitmap(openFileDialog1.FileName);
setImage.Size = loadedImage.Size;
setImage.BackgroundImage = loadedImage;
imageWidth.Text = loadedImage.Size.Width.ToString();
imageHeight.Text = loadedImage.Size.Height.ToString();
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
after opening the Image I need to be able to export the dimensions of the image to XML but I also want to export the image path there as well.
Below is the code I'm using to export as you can see I haven't done the image export as I'm unsure what to do there
private void exportButton_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
DataTable xyPos = new DataTable();
xyPos.TableName = "Position";
xyPos.Columns.Add("X");
xyPos.Columns.Add("Y");
ds.Tables.Add(xyPos);
DataTable whDimen = new DataTable();
whDimen.TableName = "Dimensions";
whDimen.Columns.Add("Width");
whDimen.Columns.Add("Height");
ds.Tables.Add(whDimen);
DataTable loadImage = new DataTable();
loadImage.TableName = "LoadedImage";
loadImage.Columns.Add("Image");
ds.Tables.Add(loadImage);
DataRow posRow = ds.Tables["Position"].NewRow();
posRow["X"] = Xcoord.Text;
posRow["Y"] = Ycoord.Text;
ds.Tables["Position"].Rows.Add(posRow);
DataRow dimenRow = ds.Tables["Dimensions"].NewRow();
dimenRow["Width"] = imageWidth.Text;
dimenRow["Height"] = imageHeight.Text;
ds.Tables["Dimensions"].Rows.Add(dimenRow);
//Export Image
DataRow imageRow = ds.Tables["LoadedImage"].NewRow();
imageRow["Image"] = setImage.BackgroundImage;
//ImageConverter imgConvert = new ImageConverter();
//byte[] imgByte = (byte[])imgConvert.ConvertTo(imageRow["Image"], typeof(byte[]));
//Convert.ToBase64String(imgByte);
//Convert.ToBase64String((byte[])imageRow["Image"]);
ds.Tables["LoadedImage"].Rows.Add(imageArray);
ds.WriteXml("XMLFile1.xml");
}

Read and change values of a gridview in c#

I am working on an csv changing tool for magento.
This tool has to change some values of a csv file.
I have already imported the csv into a gridview.
My question is how do you Read a value of a single cell and change it from a gridview.
I am using the windows form c#
i want something like this:
imput:
EAN,Product code,name
363738492,MT-01234,iphone case
153289234,MT-89854,samsung case
876253483,PO-43466,network cable
output:
EAN,sku,name
363738492,MT-01234,iphone case
153289234,MT-89854,samsung case
876253483,PO-43466,network cable
this is my working import code:
private void Import_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Select file";
fdlg.InitialDirectory = #"c:\";
fdlg.FileName = txtFileName.Text;
fdlg.Filter = "Text and CSV Files(*.txt, *.csv)|*.txt;*.csv|Text Files(*.txt)|*.txt|CSV Files(*.csv)|*.csv|All Files(*.*)|*.*";
fdlg.FilterIndex = 1;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
txtFileName.Text = fdlg.FileName;
Import();
Application.DoEvents();
}
}
public static DataTable GetDataTable(string strFileName)
{
ADODB.Connection oConn = new ADODB.Connection();
oConn.Open("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\";", "", "", 0);
string strQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(strFileName) + "]";
ADODB.Recordset rs = new ADODB.Recordset();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter();
DataTable dt = new DataTable();
rs.Open(strQuery, "Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\";",
ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly, 1);
adapter.Fill(dt, rs);
return dt;
}
private void Import()
{
if (txtFileName.Text.Trim() != string.Empty)
{
try
{
DataTable dt = GetDataTable(txtFileName.Text);
dgvGv.DataSource = dt.DefaultView;
dgvGv2.DataSource = dt.DefaultView;
dgvGv3.DataSource = dt.DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
this is my working export code:
private void button1_Click(object sender, EventArgs e)
{
// Don't save if no data is returned
if (dgvGv.Rows.Count == 0)
{
return;
}
StringBuilder sb = new StringBuilder();
// Column headers
string columnsHeader = "";
for (int i = 0; i < dgvGv.Columns.Count; i++)
{
columnsHeader += dgvGv.Columns[i].Name + ",";
}
sb.Append(columnsHeader + Environment.NewLine);
// Go through each cell in the datagridview
foreach (DataGridViewRow dgvRow in dgvGv.Rows)
{
// Make sure it's not an empty row.
if (!dgvRow.IsNewRow)
{
for (int c = 0; c < dgvRow.Cells.Count; c++)
{
// Append the cells data followed by a comma to delimit.
sb.Append(dgvRow.Cells[c].Value + ",");
}
// Add a new line in the text file.
sb.Append(Environment.NewLine);
}
}
// Load up the save file dialog with the default option as saving as a .csv file.
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "CSV files (*.csv)|*.csv";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// If they've selected a save location...
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(sfd.FileName, false))
{
// Write the stringbuilder text to the the file.
sw.WriteLine(sb.ToString());
}
}
// Confirm to the user it has been completed.
MessageBox.Show("CSV file saved.");
}
feel free to comment for any questions.
/Select CSV File from drop down then click Import from /In Button Clink Event
private void btnimportexcel_Click(object sender, EventArgs e)
{
string source = string.Empty;
source = cmbImportsource.Text;
if (!string.IsNullOrEmpty(source ))
{
string smsfilename=string .Empty ;
OpenFileDialog of = new OpenFileDialog();
DialogResult dlresult;
of.InitialDirectory = Environment.SpecialFolder.Desktop.ToString ();
switch (source)
{
case "EXCEL":
of.Filter = "Excel File(*.xlsx,*.xls)|*.xlsx;*.xls|All Files(*.*)|*.*";
of.Title = "Select Excel File...";
dlresult = of.ShowDialog();
if (dlresult == DialogResult.OK )
{
smsfilename = of.FileName;
if (System.IO.File.Exists(smsfilename))
{
getRecordFromXcel(smsfilename);
}
}
break;
case "CSV":
//"Text and CSV Files(*.txt, *.csv)|*.txt;*.csv|Text Files(*.txt)|*.txt|CSV Files(*.csv)|*.csv|All Files(*.*)|*.*";
of.Filter = "CSV Files(*.csv)|*.csv|All Files(*.*)|*.*";
of.Title = "Select Excel File...";
dlresult = of.ShowDialog();
if (dlresult == DialogResult.OK )
{
smsfilename = of.FileName;
if (System.IO.File.Exists(smsfilename))
{
getRecordFromCSV(smsfilename);
}
}
break;
case "TEXT FILE":
break;
}
}
//When File Selected
private void getRecordFromCSV(string file)
{
String textLine = string.Empty;
String[] splitLine;
bool columncreater = false;
try
{
StreamReader objReaders = new StreamReader(file);
dataGridView1.DataSource = null;
dataGridView1.Columns.Clear();
dataGridView1.Rows.Clear();
int datagridrowindex =-1;
do
{
textLine = objReaders.ReadLine();
datagridrowindex= datagridrowindex + 1;
if (textLine != "")
{
splitLine = textLine.Split(',');
//if (splitLine[0] != "" || splitLine[1] != "")
//{
// dataGridView1.Rows.Add(splitLine[0]);
//}
if (columncreater ==false )
{
for (int i = 0; i < splitLine.Length; i++)
{
dataGridView1.Columns.Add("C" + i + "", "C" + i + "");
}
columncreater = true;
}
dataGridView1.Rows.Add(splitLine);
int cc = dataGridView1.Columns.Count;
int rr = dataGridView1.Rows.Count;
}
} while (objReaders.Peek() != -1);
}
catch (Exception ex)
{
}
}

c# Get File Name

private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog newOpen = new OpenFileDialog();
DialogResult result = newOpen.ShowDialog();
this.textBox1.Text = result + "";
}
It just returns "OK"
What am I doing wrong? I wish to get the PATH to the file and display it in a text box.
The ShowDialog method returns whether the user pressed OK or Cancel. This is useful information, but the actual filename is stored as a property on the dialog
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog newOpen = new OpenFileDialog();
DialogResult result = newOpen.ShowDialog();
if(result == DialogResult.OK) {
this.textBox1.Text = newOpen.FileName;
}
}
You need to access the filename:
string filename = newOpen.FileName;
or filenames, if you allowed multiple file selection:
newOpen.FileNames;
Ref.: OpenFileDialog Class
private void button1_Click(object sender, System.EventArgs e) {
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\" ;
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file. Error: " + ex.Message);
}
}
}
You need to read the FileName property of the OpenFileDialog instance. This will get you the path of the selected file.
Here is an example of using an existing file as a default, and getting a new file back:
private string open(string oldFile)
{
OpenFileDialog newOpen = new OpenFileDialog();
if (!string.IsNullOrEmpty(oldFile))
{
newOpen.InitialDirectory = Path.GetDirectoryName(oldFile);
newOpen.FileName = Path.GetFileName(oldFile);
}
newOpen.Filter = "eXtensible Markup Language File (*.xml) |*.xml"; //Optional filter
DialogResult result = newOpen.ShowDialog();
if(result == DialogResult.OK) {
return newOpen.FileName;
}
return string.Empty;
}
Path.GetDirectoryName(file) : Return path
Path.GetFileName(file) : Return filename

PDFBox throws exception: NullReference Exception

pdfbox issue
I used pdfbox to extract text from PDF to my richtextbox.
I don't know what's the problem but there are PDF that are good but there are PDF that throws an exception, the exception is:
Object reference not set to an instance of an object.
Here's my code:
using org.pdfbox.pdmodel;
using org.pdfbox.util;
private void pdfButton_Click(object sender, EventArgs e)
{
OpenFileDialog openFD = new OpenFileDialog();
openFD.FileName = "";
openFD.InitialDirectory = "C:\\";
openFD.Filter = "All PDF Files|*.PDF";
openFD.Title = "Browse all PDF files";
if (openFD.ShowDialog() == DialogResult.OK)
{
try
{
pdf_filename = Path.GetFileNameWithoutExtension(openFD.Filename);
PDDocument pdfFile = PDDocument.load(openFD.Filename);
PDFTextStripper pdfStripper = new PDFTextStripper();
richtextBox1.Text = pdfStripper.getText(pdfFile);
textBox1.Text = Path.GetFileName(openFD.Filename);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
}
I fixed the issue using iTextSharp. This was advised by my co-worker, I changed the PDFBox by iTextSharp.
If someone will have the same issue as me here's the working code:
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
private void pdfButton_Click(object sender, EventArgs e)
{
OpenFileDialog openFD = new OpenFileDialog();
openFD.FileName = "";
openFD.InitialDirectory = "C:\\";
openFD.Filter = "All PDF Files|*.PDF";
openFD.Title = "Browse all PDF files";
if (openFD.ShowDialog() == DialogResult.OK)
{
try
{
pdf_filename = Path.GetFileNameWithoutExtension(openFD.Filename);
richtextBox1.Text = ReadPdf(openFD.FileName);
textBox1.Text = Path.GetFileName(openFD.Filename);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
}
private string ReadPdf(string filename)
{
if (!File.Exists(filename)) return string.Empty;
PdfReader reader = new PdfReader(filename);
string text = string.Empty;
for (int page = 1; page <= reader.NumberOfPages; page++)
{
text += PdfTextExtractor.GetTextFromPage(reader, page);
}
return text;
}

Categories

Resources