Importing CSV to Dataset Problem

G

Gregory Pearce

Hi everyone
Can anybody please help me? I am trying to write my first project in ASP.
NET (C#) and I am having some issues trying import a CSV file to populate
the form with values

I have a basic CSV file (bookName, bookPrice) and on the PageLoad event I
perform the method as below (!=postback of course)

private void LoadBooks ()
{
string delimiter = ",";
string tableName = "BooksTable";
string fileName = Server.MapPath("/DepartmentStore/data" + "/books.txt");

DataSet dataset = new DataSet();
StreamReader sr = new StreamReader(fileName);

dataset.Tables.Add(tableName);
dataset.Tables[tableName].Columns.Add("product");
dataset.Tables[tableName].Columns.Add("price");

string allData = sr.ReadToEnd();
string[] rows = allData.Split("\r\n".ToCharArray());

foreach(string r in rows)
{
string[] items = r.Split(delimiter.ToCharArray());
dataset.Tables[tableName].Rows.Add(items);
}
}

What I would like to do is now populate the form from the values that have
been imported into the datatable however, I am not sure how to call it. In
the same method, I would like to have something that says lblBook1.Text =
item[0] or something like that. (I have a CSV file with 6 books in it) Not
sure if I am on the right track. From what I understand, I have created a
dataset, added a table with two colums, read the entire text file, and split
the row at the delimiter.

Sorry for the newbie question, but any help would be very appreciated.

Greg :)
 
A

Alex Passos

You can attach the DataSet directly with a DataGrid object to render on your
ASP.NET app or you can access each of the rows yourself and render them like
this:

string col1="";
string col2="";
for(i = 0; i < dataset.Tables[tablename].Rows.Count) {
col1 = dataset.Tables[tablename].Rows[0]; // row i column 0
col2 = dataset.Tables[tablename].Rows[1]; // row i column 1
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top