Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a data table having multiple column which is coming from DB.Now I need to add one column from a text file as the first column.Below format is my text file

ID		
----  
val1      
val3      
val5


below is my table creation code and i am getting data table with DB values .How i can add my txt file as first column

What I have tried:

C#
private static DataTable LoadTable(string connectionString, string query, string tableName)
        {
            using (var connection = new OdbcConnection(connectionString))
            using (var command = new OdbcCommand(query, connection))
            using (var adapter = new OdbcDataAdapter(command))
            {
                command.CommandTimeout = 0;
                var table = new DataTable(tableName);
                adapter.Fill(table);
                return table;
            }
        }
Posted
Updated 8-Dec-21 4:11am
v2

1 solution

Try this:
string strConnect = SMDBSupport.SMInstanceStorage.GetInstanceConnectionString("MyDatabase");
using (SqlConnection con = new SqlConnection(strConnect))
    {
    try
        {
        con.Open();
        using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM MyTable", con))
            {
            DataTable dt = new DataTable();
            da.Fill(dt);
            dt.Columns.Add("My New Column", typeof(string)).SetOrdinal(0);
            myDataGridView.DataSource = dt;
            }
        }
    catch (Exception ex)
        {
        Debug.WriteLine(ex.ToString());
        }
    }
You can then set the values of your DT to the text file lines.
 
Share this answer
 
v2
Comments
[no name] 8-Dec-21 10:24am    
I dont have any data grid view.I am using OLEDB connection.This is not working for me.I have text file out there I need to use that to get the data and to add in to existing DT
OriginalGriff 8-Dec-21 10:53am    
So don't use the DGV ... That's just there to show you how I do it ...
[no name] 8-Dec-21 11:38am    
how do i access my outside .txt file here?
OriginalGriff 8-Dec-21 11:53am    
You are kidding, right?
You are playing with DB's and DT's and you have no idea how to read a *text file*?
[no name] 8-Dec-21 12:55pm    
if (tableName == "TestData")
{

var pathC = @"H:\Oneroof\SyntheticData\Claims.txt";

var fileContents = File.ReadAllLines(pathC);

var splitFileContents = (from f in fileContents select f.Split(':')).ToArray();

int maxLength = (from s in splitFileContents select s.Count()).Max();

for (int i = 0; i < maxLength; i++)
{
table.Columns.Add();
}

foreach (var line in splitFileContents)
{
DataRow row = table.NewRow();
row.ItemArray = (object[])line;
table.Rows.Add(row);
}


}




return table;

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