Click here to Skip to main content
15,917,586 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I am creating a windows form application in C#. I have created a table with the name of(h-index).and now I have to add data in the table by reading the data from a notepad file. Can you help me in this problem ?????
Posted
Updated 12-May-14 19:06pm
v2
Comments
DamithSL 13-May-14 1:18am    
Ok Fine, you have set of requirements , what have you tried?

Hi,

Please refer following code.

1) First, read the file line by line and save in list.

XML
List<string> myValues = new List<string>();
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
   new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
   myValues.Add(line);
}


2) Then open a DB-Connection to your DB via OleDB and insert the values into your database via an INSERT INTO Statement.

C#
private void InsertMyValue(string myValue){
     dbconnection.Open();
     string setValues = "INSERT INTO YourTable(myColumn) VALUES ('" + myValue+ "');";
     OleDbCommand cmd = new OleDbCommand(setValues, dbconnection);
     cmd.ExecuteNonQuery();
     dbconnection.Close();
}


3) Then call the method in a foreach - clause

SQL
foreach(string myLine in myValues){ //Go through the List with all the Lines
       dbconnection.InsertMyValue(myLine); //Get every item in the List and call the Insert-Method
}


You can refer linkhttp://stackoverflow.com/questions/14922360/insert-data-from-a-text-file-into-a-table-in-c-sharp

Thanks,
Bh@gyesh
 
Share this answer
 
Comments
[no name] 13-May-14 1:08am    
good job!!
If the text file is a delimited file or a fixed column length file, you can connect to it OleDb connection and read data by querying it.
 
Share this answer
 
XML
OleDbCommand cmd  = new  OleDbCommand("",new OleDbConnection("Replace Your Connection string here"));
        cmd.Connection.Open();
        System.IO.File.ReadAllLines(@"C:\testfiles\testfile.txt").ToList<string>().ForEach(delegate(string InsertingValue)
        {
            cmd.CommandText = "Insert into YourTable(ColumnName) VALUES ('" + InsertingValue + "');";
            cmd.ExecuteNonQuery();
        });



Replace The file path with your file path
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900