0

Im trying to read in 3 columns of info (student id, name, subject) into a datatable from a database using a oledb connection. It loads fine and i can get it into a datatable no problem. I then output the datable to a datagridview. Now what i cant figure out how to do is to add 2 more columns after the 3 columns read from the database into the same table and display the now 5 column table to the datagridview. THe two columns of info will come from a list. Can anyone provide an example on how to do this?

Thanks

1 Answer 1

2

Now this is heavily abbreviated, and makes many assumptions (i.e. the order of items returned from the query is the same as the order of items in your lists). But this is the basic idea.

string columnFourName = "Col4";
string columnFourName = "Col5";
List<object> columnFourItems = new List<object>()
List<object> columnFiveItems = new List<object>()
SqlConnection oConn = new SqlConnection("SomeConnstring);
oConn.Open();
SqlCommand oComm = new SqlCommand("SELECT * FROM Stuff", oConn);
SqlDataAdapter sda = new SqlDataAdapter(oComm);
DataTable dt = new DataTable();
sda.Fill(dt);
dt.Columns.Add(columnFourName, typeof(object));
dt.Columns.Add(columnFiveName, typeof(object));
for (int row = 0; row < dt.Rows.Count; row++)
{
    dt.Rows[row][3] = columnFourItems[row];
    dt.Rows[row][4] = columnFiveItems[row];
}
Sign up to request clarification or add additional context in comments.

3 Comments

okay im having a problem. Once i fill the info into columns from the datatable and add a new column by hand, when i populate that olumn, the data gets added to the next row in the datagridview. so it looks like: ID Name Subject 1 Hi Math
@Greg - I am not sure that I follow completely. Could you edit your question so I can see what it looks like formatted?
Sorry i think i just figured it out. It just required a little tweaking. THanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.