I have an excel table with multiple rows, and when I import my .csv file it only displays the first row.
What I want is to fill the list with every row.
cargarCSV() = load .csv file
validar() = pass the csv file to the listview
private void cargarCSV() //Load .csv
{
OpenFileDialog dialogoCargar = new OpenFileDialog();
dialogoCargar.Filter = "Archivos CSV|*.csv";
dialogoCargar.FilterIndex = 1;
if(dialogoCargar.ShowDialog() == DialogResult.OK)
{
filepath = dialogoCargar.FileName;
txtbox_ArchivoCargado.Text = filepath;
}
}
private void Validar() //Pass .csv to ListView
{
empleadosValido = true;
try {
FileStream fileStreamNew = File.Open(filepath, FileMode.Open, FileAccess.ReadWrite);
StreamReader streamRead = new StreamReader(fileStreamNew);
string strView = streamRead.ReadToEnd();
streamRead.Close();
fileStreamNew.Close();
String[] strArray = strView.Split(new char[] { ',' });
ListViewItem item = new ListViewItem(strArray[0].ToString());
item.SubItems.Add(strArray[1].ToString());
item.SubItems.Add(strArray[2].ToString());
item.SubItems.Add(strArray[3].ToString());
item.SubItems.Add(strArray[4].ToString());
item.SubItems.Add(strArray[5].ToString());
item.SubItems.Add(strArray[6].ToString());
list_Previ.Items.Add(item);
}catch (Exception ex)
{
if (ex is IOException)
{
MessageBox.Show("El archivo se encuentra en uso por otro programa\nPor favor cierra otros programas e intenta de nuevo.", "Corporativo Acosta | Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
empleadosError = true;
MessageBox.Show(ex.ToString());
}
if (ex is IndexOutOfRangeException)
{
MessageBox.Show("Hay un problema con tus columnas.\nVerifica que correspondan las columnas a importar\ncon las de la tabla (7 columnas)", "Corporativo Acosta | Error", MessageBoxButtons.OK ,MessageBoxIcon.Error);
empleadosError = true;
MessageBox.Show(ex.ToString());
}
}
}
Without changing too much of your actual code, but insering a loop for each line present in your file you should go for
foreach(string strView = File.ReadLines(filepath))
{
String[] strArray = strView.Split(new char[] { ',' });
ListViewItem item = new ListViewItem(strArray[0].ToString());
item.SubItems.Add(strArray[1].ToString());
item.SubItems.Add(strArray[2].ToString());
item.SubItems.Add(strArray[3].ToString());
item.SubItems.Add(strArray[4].ToString());
item.SubItems.Add(strArray[5].ToString());
item.SubItems.Add(strArray[6].ToString());
list_Previ.Items.Add(item);
}
Of course you could remove all of your references to the FileStream and StreamReader variables.
Also, if you forecast that some of your lines contains less than 7 elements, I suggest to add a check for the array length just before adding the element to the ListView Items collection and do not rely on exception handling to continue. Using exceptions to drive your code is a bad practice and hitting an exception is costly in terms of performance ( a lot more than putting an if before adding the elements), so something like this should considered
if(strArray.Length > 1) item.SubItems.Add(strArray[1].ToString());
if(strArray.Length > 2) item.SubItems.Add(strArray[2].ToString());
....
Related
I need to upload an attachment to a MS Access .mdb, nonetheless, the code runs until the end, but nothing gets updated.
Reviewing the query syntax and checking the OleDbTypes that are used in the code.
protected void Button1_Click(object sender, EventArgs e)
{
mdlTrab mdl = new mdlTrab();
mdl.nome = txtNome.Text;
mdl.trab = titTrab.Text;
mdl.campo = FileUpload1.FileBytes;
if (FileUpload1.HasFile)
{
try
{
string fileExtension = Path.GetExtension(FileUpload1.FileName);
if (fileExtension.ToLower() == ".doc" || fileExtension.ToLower() == ".docx" || fileExtension.ToLower() == ".pdf")
{
if (FileUpload1.PostedFile.ContentLength > 1024000)
{
StatusLabel.ForeColor = System.Drawing.Color.Red;
StatusLabel.Text = "Status do upload: O arquivo deve ter menos de 1000 kb!";
}
else
{
string conexaoAccess = ConfigurationManager.ConnectionStrings["conexaoAccess"].ToString();
using (OleDbConnection conexaodb = new OleDbConnection(conexaoAccess))
{
conexaodb.Open();
OleDbCommand cmd = new OleDbCommand("UPDATE tbl_reg SET Campo1 = #campo, titulo_trab = #trab WHERE nome_user = #nome", conexaodb);
cmd.Parameters.Add("#campo", OleDbType.LongVarBinary).Value = mdl.campo;
cmd.Parameters.Add("#trab", OleDbType.LongVarChar).Value = mdl.trab;
cmd.Parameters.Add("#nome", OleDbType.LongVarChar).Value = mdl.nome;
int rowsChanged = cmd.ExecuteNonQuery();
StatusLabel.ForeColor = System.Drawing.Color.Green;
StatusLabel.Text = "Arquivo carregado!";
}
}
}
else
{
StatusLabel.ForeColor = System.Drawing.Color.Red;
StatusLabel.Text = "Status do upload: Somente arquivos .doc, .docx e .pdf são aceitos!";
}
}
catch (InvalidOperationException ex)
{
StatusLabel.ForeColor = System.Drawing.Color.Red;
StatusLabel.Text = "Status do upload: Erro ao carregar arquivo, ocorreu o seguinte erro: " + ex.Message;
}
catch (OleDbException ex)
{
StatusLabel.ForeColor = System.Drawing.Color.Red;
StatusLabel.Text = "Status do upload: Erro ao atualizar banco de dados, erro oorrido: " + ex.Message;
}
catch (Exception ex)
{
Console.WriteLine("Erro: ", ex.Message);
}
}
}
The Model
public class mdlTrab
{
public int codigo { get; set; }
public string nome { get; set; }
public string trab { get; set; }
public byte[] campo { get; set; }
}
Expected: Upload the file in the database.
Actual results: no results
You need to call ExecuteNonQuery to effectively execute the command but there is another error that you need to fix. With OleDb, parameters are not recognized by their name but by their position in the command text.
You need to add the parameters in the exact order in which they appear in your command and so, rearrange the code lines in this order
cmd.Parameters.Add("#campo", OleDbType.LongVarBinary).Value = mdl.campo;
cmd.Parameters.Add("#trab", OleDbType.LongVarChar).Value = mdl.trab;
cmd.Parameters.Add("#nome", OleDbType.LongVarChar).Value = mdl.nome;
and finally call
int rowsChanged = cmd.ExecuteNonQuery();
Of course, all the comments above about the empty try/catch are very important. If you do not handle the exception (for example writing to a log file or displaying a message) then it is better to remove the try/catch block.
Another point that you should consider is the disposing of the connection object. This object keeps internally unamanaged resources and you need to free them as soon as possible. So you should use the using statement
string conexaoAccess = ".....";
using(OleDbConnection conexaodb = new OleDbConnection(conexaoAccess))
{
conexaodb.Open();
... create the command, add parameters and execute the command
} // Here the connection will be closed and disposed
Solved by inserting an hyperlink to the file into the field, for what I was looking for it was the best approach, DAO just wouldn´t attend to my needs:
Pasting a hyperlink value from C# to Access
Appreciate the help. Thank you folks!
Im Attempting to read a .txt file that is seperated by commas and two lines, currently i have it setup so that it reads the txt file but having trouble with using the.split method with the taxArray, i need to use the .split so i can calulate the differnt values.
string[] taxArray = new string[2];
int count = 0;
try
{
if(File.Exists(filePath))
{
//read the lines from text file add each line to its own array index.
foreach (string line in File.ReadLines(filePath, Encoding.UTF8))
{
taxArray[count] = line;
txtDisplay.Text += taxArray[count] + "\r\n";
count++;
}
}
else
{
MessageBox.Show("This file cannot be found");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
This currently outputs exactly as i need.
Here was my solution, I was calling to the array before the foreach loop did its job reading the txt file, thanks for the assistance Toby <3
string[] taxArray = new string[2];
int count = 0;
// string incomeBracket = taxArray[0];
//string[] incomeBracketArray = incomeBracket.Split(',');
try
{
if(File.Exists(filePath))
{
//read the lines from text file add each line to its own array index.
foreach (string line in File.ReadLines(filePath, Encoding.UTF8))
{
taxArray[count] = line;
txtDisplay.Text += taxArray[count] + "\r\n";
count++;
}
string[] incomeBracket = taxArray[1].Split(',');
txtDisplay.Text = incomeBracket[0];
else
{
MessageBox.Show("This file cannot be found");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
I have a method inside a class that will receive a PictureBox and a String, so the user can select the image for the PictureBox and at the same time for the program to know what file plus extension of the chosen file for later use.
The string it will be set, for example as 1.png but on the where I call this method the string it will be as "" rly don't understand why this is happening.
On the GerirDoc.cs I define the string as String _imgFile = "" at the beginning of the Form and have this code:
DocImg docImg = new DocImg();
docImg.selectImage(_imgFile, this.pictureBoxDoc);
The class DocImg
class DocImg
{
public int Hwnd { get; private set; }
public void selectImage(String imgFile, PictureBox imgBox)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = "Escolher imagem";
openFileDialog.Filter = "Image files (*.jpg, *.jpeg, *.png) | *.jpg; *.jpeg; *.png";
openFileDialog.Multiselect = false;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
imgFile = openFileDialog.SafeFileName;
DialogResult dialogResult = MessageBox.Show("Deseja passar a imagem para o aparelho se tiver ligado ao computador?", "Informação", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
imgBox.Image = Image.FromFile(openFileDialog.FileName);
switch (dialogResult)
{
case DialogResult.Yes:
Shell shell = new Shell();
Folder folder = shell.BrowseForFolder((int)Hwnd, "Selecione o caminho para a pasta \"Imagens\"", 0, 0);
if (folder != null)
{
FolderItem _destinationDir = (folder as Folder3).Self;
if (String.Equals(_destinationDir.Name, "Imagens"))
{
try
{
folder.CopyHere(openFileDialog.FileName, null);
MessageBox.Show("Imagem guardada com sucesso", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
else
{
MessageBox.Show("A pasta de destino tem que ser a pasta \"Imagens\" que se está dentro de adbRetail");
}
}
break;
case DialogResult.No:
MessageBox.Show("De lembrar que a imagem só ira aparecer correctamente se tiver na pasta correcta do aparelho", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information);
break;
}
}
}
}
I did put a breakpoint just after imgFile = openFileDialog.SafeFileName; and the variable imgFile as the value of the filename, ex 1.png, but on GerirDoc.cs after choosing the file of the image, _imgFile doesn't have any value.
On GerirDoc.cs I only put _imgFile = "" when the form is created. Why is this happening ? Since I send the string inside it and since in DocImg if the user chose a image it should have the filename, ex 1.png and not be empty
As I can understand you want method to change your local variable. You should change it to:
public void selectImage(out string imgFile, PictureBox imgBox)
notice the parameter modifier out. And then call this method like this:
docImg.selectImage(out _imgFile, this.pictureBoxDoc);
The out keyword causes arguments to be passed by reference. It is like the ref keyword, except that ref requires that the variable be initialized before it is passed.
More reference here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier
Title explains a small part so let me explain 2 scenarios. Scenario 1 is raising errors, scenario 2 works like a charm.
Scenario 1:
I checkout a document with the method below, when the document is saved to a location where already is a file with that name it gets overwritten, But surprisingly it also locks the file for some reason:
public bool SaveDocument(int bestandsId, string fileName, string path)
{
//Initialize the Sql Query
var sql = "SELECT DATA FROM Documenten WHERE BESTAND_ID = " + bestandsId;
//Initialize SqlConnection
var connection = new SqlConnection(Instellingen.Instance.DmsConnectionString);
//Initialize SqlCommand
var command = new SqlCommand(sql, connection);
try
{
//Open Connection
connection.Open();
//Fill 'data' from command.ExecuteScalar()
var data = (byte[]) command.ExecuteScalar();
//Write 'data' to file.
File.WriteAllBytes(path + #"\" + fileName, data);
//Return true if no exceptions are raised.
return true;
}
catch (Exception ex)
{
//Initialize Dms Exception
var dmsEx = new DmsException(ex);
//Write Dms Exception to Log File.
DmsException.WriteErrorsToLog(dmsEx);
//Return false, because something went wrong...
return false;
}
finally
{
//Close Sql Connection
connection.Close();
}
}
The method runs smoothly. No problems occur. But when I check in the document with the method below, I get this exception:
Scenario 2:
When I use the SaveDocument method to save the document to a location where there isn't a file with the same name, the file is newly created and is ready to be edited or what ever you want to do with it.
Using scenario 2 is working perfect. The document is ready to be checked in again without receiving an error as shown in the picture above.
Request for code by: #CodeCaster
---------------------------------BEGIN EDIT---------------------------------
public static bool InsertDocument(Document document)
{
try
{
//Exception is thrown when Initializing the FileStream
var fileStream = new FileStream(document.Fileinfo.FullName, FileMode.Open, FileAccess.Read);
var binaryReader = new BinaryReader(fileStream);
var totalNumberOfBytes = new FileInfo(document.Fileinfo.FullName).Length;
var data = binaryReader.ReadBytes((Int32) totalNumberOfBytes);
fileStream.Close();
fileStream.Dispose();
binaryReader.Close();
binaryReader.Dispose();
var pdftext = string.Empty;
try
{
if (document.DocumentType == ".pdf")
{
var reader = new PdfReader(document.Fileinfo.FullName);
var text = string.Empty;
for (var page = 1; page <= reader.NumberOfPages; page++)
{
text += PdfTextExtractor.GetTextFromPage(reader, page);
}
reader.Close();
pdftext = text;
}
}
catch (Exception ex)
{
var dmsEx = new DmsException(ex);
DmsException.WriteErrorsToLog(dmsEx);
}
return InsertIntoDatabase(document.BestandsNaam, document.Eigenaar, document.Omschrijving,
document.DatumToevoeg.ToString(), document.DatumIncheck.ToString(),
document.DatumUitcheck.ToString(), document.UitgechecktDoor,
document.DocumentType, data, pdftext, document.Versie, document.Medewerker,
document.DossierNummer, document.PersonalFolderId.ToString(),
document.DossierFolderId, -1, document.DocumentProgres,
document.OriBestandId.ToString(), 0);
}
catch (Exception ex)
{
var dmsEx = new DmsException("Fout bij inlezen voor toevoeging van nieuw document",
"Klasse Document (InsertDocument)", ex);
ExceptionLogger.LogError(dmsEx);
return false;
}
}
---------------------------------END EDIT---------------------------------
My questions:
What is the cause for the file being locked when it gets overwritten?
How can I prevent this from happening?
Is there some sort of function or parameter that I can set so it doesn't get locked?
Using a tool called "Unlocker" I managed to see what program is locking the file, and YES -> DMS.exe is my application.......:
using(var stream = File.Create(newPath)){}
File.WriteAllBytes(newPath, item.File);
With StreamWriter
using (FileStream fs = File.Create(newPath))
{
fs.Write(item.File, 0, item.File.Length);
}
Or:
File.WriteAllBytes(newPath, item.File);
Reference: "The process cannot access the file because it is being used by another process" with Images
I am using a listview, and trying to populate using a file.
I need the file to be read in as soon as the form starts.
private void mainForm_Load(object sender, EventArgs e)
{
//get file read in
if (File.Exists("../../MealDeliveries.txt"))
{
StreamReader sr = new StreamReader("../../MealDeliveries.txt");
//first line is delivery name
string strDeliveryName = sr.ReadLine();
do
{
//other lines
Delivery d = new Delivery(strDeliveryName, sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine());
mainForm.myDeliveries.Add(d);
//check for further values
strDeliveryName = sr.ReadLine();
//stop if no more values
} while (strDeliveryName != null);
displayDeliveries();
}
}
private void displayDeliveries()
{
lstDeliveryDetails.Items.Clear();
foreach (Delivery d in mainForm.myDeliveries)
{
lstDeliveryDetails.Items.Add(d.DeliveryName);
}
}
The listview isn't displaying anything, although the file is definately there!
Yes, it should assuming that the file is in the place you think it is. Are you positive that the file exists?
Try this. It will at least confirm whether or not the file is found.
private void mainForm_Load(object sender, EventArgs e)
{
string fileName = #"..\..\MealDeliveries.txt";
if (!File.Exists(fileName))
{
MessageBox.Show("File not found!");
return;
}
using (StreamReader sr = new StreamReader(fileName))
{
//first line is delivery name
string strDeliveryName = sr.ReadLine();
while (strDeliveryName != null)
{
//other lines
Delivery d = new Delivery(strDeliveryName, sr.ReadLine(),
sr.ReadLine(), sr.ReadLine(),
sr.ReadLine(), sr.ReadLine(),
sr.ReadLine());
mainForm.myDeliveries.Add(d);
//check for further values
strDeliveryName = sr.ReadLine();
}
}
displayDeliveries();
}
Another thing to watch out for is reading lines in as a string to pass to your business object (Delivery). You might find it better to use some sort of serialization format provided by XmlSerializer or one of the file formats supported by Marcos Meli's FileHelpers library. Either way, something more robust than reading in strings would be desirable.
Maybe it will work but you also need to wrap IDisposables with using. Like this:
using (StreamReader sr = new StreamReader("../../MealDeliveries.txt"))
{
//first line is delivery name
string strDeliveryName = sr.ReadLine();
do
{
//other lines
Delivery d = new Delivery(strDeliveryName, sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine());
mainForm.myDeliveries.Add(d);
//check for further values
strDeliveryName = sr.ReadLine();
//stop if no more values
} while (strDeliveryName != null);
displayDeliveries();
}