473,379 Members | 1,326 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

Opening and importing Multiple files into DataGridView + database

80 64KB
I'm trying to add a function now that lets the user open 1 or more files and import them to the database and dataGridView. Now the way it is now (should) work. But when it has finished with FILE1, it won't add FILE2 as it then gives me an error that the Column Date Already exists. Any ideas?


My code is below


Expand|Select|Wrap|Line Numbers
  1. private void btnOpenLog_Click(object sender, EventArgs e)
  2.         {
  3.             OpenFileDialog openFileDialog1 = new OpenFileDialog();
  4.             openFileDialog1.Filter = "Log Files (*.log)|*.log";
  5.             openFileDialog1.Multiselect = true;
  6.             openFileDialog1.CheckFileExists = true;
  7.             openFileDialog1.RestoreDirectory = false;
  8.  
  9.             //string initDir = "C:/Logs";
  10.  
  11.             //openFileDialog1.InitialDirectory = !Directory.Exists(initDir) ? Path.GetPathRoot(Environment.SystemDirectory) : initDir;
  12.  
  13.             if (openFileDialog1.ShowDialog() != DialogResult.Cancel)
  14.             {
  15.                 foreach (String file in openFileDialog1.FileNames)
  16.                 {
  17.                     try
  18.                     {
  19.                         dataGridView1.DataSource = LoadTable(file);
  20.  
  21.                         using (SQLiteConnection conn = new SQLiteConnection(connString))
  22.                         {
  23.                             using (SQLiteCommand command = new SQLiteCommand())
  24.                             {
  25.                                 conn.Open();
  26.  
  27.                                 command.Connection = conn;
  28.                                 command.CommandText = "insert into Test ([Date], [LogName], [Channel], [DateRecord], [SizeInBytes]) values" + "(@Date, @LogName, @Channel, @DateRecord, @SizeInBytes)";
  29.  
  30.                                 command.Parameters.Add("@Date", DbType.String);
  31.                                 command.Parameters.Add("@LogName", DbType.String);
  32.                                 command.Parameters.Add("@Channel", DbType.String);
  33.                                 command.Parameters.Add("@DateRecord", DbType.String);
  34.                                 command.Parameters.Add("@SizeInBytes", DbType.Int64);
  35.  
  36.                                 foreach (DataGridViewRow row in dataGridView1.Rows)
  37.                                 {
  38.                                     if (!row.IsNewRow)
  39.                                     {
  40.                                         command.Parameters["@Date"].Value = row.Cells[0].Value;
  41.                                         command.Parameters["@LogName"].Value = row.Cells[1].Value;
  42.                                         command.Parameters["@Channel"].Value = row.Cells[2].Value;
  43.                                         command.Parameters["@DateRecord"].Value = row.Cells[3].Value;
  44.                                         command.Parameters["@SizeInBytes"].Value = row.Cells[4].Value;
  45.                                         command.ExecuteNonQuery();
  46.                                     }
  47.                                     command.CommandType = CommandType.Text;
  48.                                 }
  49.                             }
  50.                             conn.Close();
  51.                         }
  52.                     }
  53.                     catch (Exception err)
  54.                     {
  55.                         MessageBox.Show("Error:  " + err.Message, "Program Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  56.                     }
  57.                 }
  58.             }
  59.         }
  60.  
  61.         private DataTable LoadTable(string filename)
  62.         {
  63.             dTable.Columns.Add(new DataColumn("Date", typeof(string)));
  64.             dTable.Columns.Add(new DataColumn("LogName", typeof(string)));
  65.             dTable.Columns.Add(new DataColumn("Channel", typeof(string)));
  66.             dTable.Columns.Add(new DataColumn("DateRecord", typeof(string)));
  67.             dTable.Columns.Add(new DataColumn("SizeInBytes", typeof(float)));
  68.  
  69.             DataRow dr;
  70.  
  71.             String sLine = new StreamReader(filename).ReadToEnd();
  72.  
  73.             if (sLine != null)
  74.             {
  75.                 foreach (string regel in Regex.Split(sLine, "\r\n"))
  76.                 {
  77.                     if (!string.IsNullOrEmpty(regel))
  78.                     {
  79.                         dr = dTable.NewRow();
  80.  
  81.                         string[] splitregel = Regex.Split(regel.Replace("|", ";"), ";");
  82.  
  83.                         dr[0] = splitregel[0];
  84.                         dr[1] = splitregel[1];
  85.                         dr[2] = splitregel[2];
  86.                         dr[3] = splitregel[3];
  87.                         dr[4] = splitregel[4];
  88.  
  89.                         dTable.Rows.Add(dr);
  90.                     }
  91.                 }
  92.             }
  93.             return dTable;
  94.         }
Mar 29 '13 #1

✓ answered by M1kkelZU

Fixed my issue lol.

It was a simple solution in the end:
Expand|Select|Wrap|Line Numbers
  1.  private DataTable LoadTable(string filename)
  2.         {
  3.             if (dTable.Columns.Count != 5)
  4.             {
  5.                 dTable.Columns.Add(new DataColumn("Date", typeof(string)));
  6.                 dTable.Columns.Add(new DataColumn("LogName", typeof(string)));
  7.                 dTable.Columns.Add(new DataColumn("Channel", typeof(string)));
  8.                 dTable.Columns.Add(new DataColumn("DateRecord", typeof(string)));
  9.                 dTable.Columns.Add(new DataColumn("SizeInBytes", typeof(float)));
  10.             }
  11.             else
  12.             {
  13.                 //huehue
  14.             }
  15.  
  16.             DataRow dr;
  17.  
  18.             String sLine = new StreamReader(filename).ReadToEnd();
  19.  
  20.             if (sLine != null)
  21.             {
  22.                 foreach (string regel in Regex.Split(sLine, "\r\n"))
  23.                 {
  24.                     if (!string.IsNullOrEmpty(regel))
  25.                     {
  26.                         dr = dTable.NewRow();
  27.  
  28.                         string[] splitregel = Regex.Split(regel.Replace("|", ";"), ";");
  29.  
  30.                         dr[0] = splitregel[0];
  31.                         dr[1] = splitregel[1];
  32.                         dr[2] = splitregel[2];
  33.                         dr[3] = splitregel[3];
  34.                         dr[4] = splitregel[4];
  35.  
  36.                         dTable.Rows.Add(dr);
  37.                     }
  38.                 }
  39.             }
  40.             return dTable;
  41.         }
basically I check to see if the columns are made, if not it makes them. from there on it does the rest of its work.

12 5234
Rabbit
12,516 Expert Mod 8TB
That's because your LoadTable function runs again on your second file. Which means it tries to add the same columns it added the first time.
Mar 29 '13 #2
M1kkelZU
80 64KB
Ah ok. So what would be a way for me to keep running if there are multiple files? I was thinking of before reading the file that it would merge all the files into 1 file, but I'd think thats a huge workaround
Mar 29 '13 #3
Rabbit
12,516 Expert Mod 8TB
Add those columns only once. Outside of the loop.
Mar 29 '13 #4
M1kkelZU
80 64KB
Expand|Select|Wrap|Line Numbers
  1.  if (sLine != null)
  2.             {
  3.                 foreach (string regel in Regex.Split(sLine, "\r\n"))
  4.                 {
  5.                     dr = dTable.NewRow();
  6.                     if (!string.IsNullOrEmpty(regel))
  7.                     {
  8.  
  9.                         string[] splitregel = Regex.Split(regel.Replace("|", ";"), ";");
  10.  
  11.                         dr[0] = splitregel[0];
  12.                         dr[1] = splitregel[1];
  13.                         dr[2] = splitregel[2];
  14.                         dr[3] = splitregel[3];
  15.                         dr[4] = splitregel[4];
  16.                     }
  17.                         dTable.Rows.Add(dr);
  18.                 }  
  19.             }
So like this?

EDIT: Read it wrong. But if I look at it, my LoadTable method adds the Columns before the loop even starts, or am I looking at it in a wrong perspective?
Mar 29 '13 #5
Rabbit
12,516 Expert Mod 8TB
No, it's in a loop.

In your original post, you call the function on line 19. It's in the loop that starts on line 15.
Mar 29 '13 #6
M1kkelZU
80 64KB
But if I get it out of the foreach loop it then says that file doesn't exist as I declare it in my foreach loop. So where would it have to move it?
Mar 29 '13 #7
Rabbit
12,516 Expert Mod 8TB
I don't mean the entire function. In post #4 I said
Add those columns only once. Outside of the loop.
Just the lines that add the columns needs to be outside the loop.
Mar 29 '13 #8
M1kkelZU
80 64KB
Sorry for the late response, was away for the Easter weekend.

I still don't quite get what you mean.
EDIT I now see what you mean, in my LoadTable Method the section
Expand|Select|Wrap|Line Numbers
  1. dTable.Columns.Add(new DataColumn("Date", typeof(string)));
  2.             dTable.Columns.Add(new DataColumn("LogName", typeof(string)));
  3.             dTable.Columns.Add(new DataColumn("Channel", typeof(string)));
  4.             dTable.Columns.Add(new DataColumn("DateRecord", typeof(string)));
  5.             dTable.Columns.Add(new DataColumn("SizeInBytes", typeof(float)));
is being run through again which causes the addition of a second column that exists.

Now I have no clue how to edit this into a fact that it works.
Apr 3 '13 #9
Rabbit
12,516 Expert Mod 8TB
Move those lines of code out before the loop.
Apr 3 '13 #10
M1kkelZU
80 64KB
I was thinking, if I add the columns once already wouldn't I just be able to use something like
Expand|Select|Wrap|Line Numbers
  1. dTable.Columns.Clear();
before starting the loop or at the end of the LoadTable method?
Apr 4 '13 #11
M1kkelZU
80 64KB
Fixed my issue lol.

It was a simple solution in the end:
Expand|Select|Wrap|Line Numbers
  1.  private DataTable LoadTable(string filename)
  2.         {
  3.             if (dTable.Columns.Count != 5)
  4.             {
  5.                 dTable.Columns.Add(new DataColumn("Date", typeof(string)));
  6.                 dTable.Columns.Add(new DataColumn("LogName", typeof(string)));
  7.                 dTable.Columns.Add(new DataColumn("Channel", typeof(string)));
  8.                 dTable.Columns.Add(new DataColumn("DateRecord", typeof(string)));
  9.                 dTable.Columns.Add(new DataColumn("SizeInBytes", typeof(float)));
  10.             }
  11.             else
  12.             {
  13.                 //huehue
  14.             }
  15.  
  16.             DataRow dr;
  17.  
  18.             String sLine = new StreamReader(filename).ReadToEnd();
  19.  
  20.             if (sLine != null)
  21.             {
  22.                 foreach (string regel in Regex.Split(sLine, "\r\n"))
  23.                 {
  24.                     if (!string.IsNullOrEmpty(regel))
  25.                     {
  26.                         dr = dTable.NewRow();
  27.  
  28.                         string[] splitregel = Regex.Split(regel.Replace("|", ";"), ";");
  29.  
  30.                         dr[0] = splitregel[0];
  31.                         dr[1] = splitregel[1];
  32.                         dr[2] = splitregel[2];
  33.                         dr[3] = splitregel[3];
  34.                         dr[4] = splitregel[4];
  35.  
  36.                         dTable.Rows.Add(dr);
  37.                     }
  38.                 }
  39.             }
  40.             return dTable;
  41.         }
basically I check to see if the columns are made, if not it makes them. from there on it does the rest of its work.
Apr 4 '13 #12
Rabbit
12,516 Expert Mod 8TB
That will work. But here's the thing, the check is unnecessary. In the original code, all you had to do was move lines 63-67 to before line 15.
Apr 4 '13 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Steve George | last post by:
Hi, I have a scenario where I have a master schema that defines a number of complex and simple types. I then have a number of other schemas (with different namespaces) where I would like to reuse...
5
by: chudson007 | last post by:
I have over three hundred text files that I need to import to SQL Server. Each is in the exact same format. I want to import tham as seperate tables. Is there any way to do it in one process? ...
0
by: bilosta | last post by:
In datatable I have field with type: "binary data", and I put into it some jpeg, doc, xls, .... files. Then I have a web form with download button, when user click it i wont to give him all files...
4
by: Kathie via AccessMonster.com | last post by:
Hello, I have to import monthly, files that were once *.csv but due to commas in addresses, the interface program was changed to dump tab delimited. Now my code is not finding the files in the...
4
by: JamesSykes | last post by:
Hi, I am relatively new to Access and VBA. I am trying to import a number of database files (just really want the contents of their tables) from a specified folder into a master table that...
28
by: kkadakia | last post by:
I get a daily excel file for a entire month which I want to transfer into Access at the end of the month. So, there are around 20-25 excel files I get by the end of the month, and I would like to...
7
by: cannunzi | last post by:
I'm trying to import multiple files in one access table all at once but i keep hitting an error stating incorrect file path. The code below works when i change the * to the exact file name but then...
4
by: myGoogle71 | last post by:
Hi, I have to import hundreds of file to MySQL database. Is it possible to write a script/storedprocedure in MySQL that does this without manually doing it for each file. Say file names are of...
10
by: kimiraikkonen | last post by:
Hi, I have an app which has a listbox and when i double click an associated fileS, i want their paths to be added into listbox in my application. This code works good when i try to open a...
1
by: aconti74 | last post by:
Hello I am new to vba programming/coding. I am writing a program that goes through a directory of text files and imports them into the database. The problem is eventually the database gets to big...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.