469,578 Members | 1,742 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,578 developers. It's quick & easy.

C# Web App: How to go through for loop adding string to datarow??

55
Hi,

I need some help in creating a dataset that I can bind to a datalist after it has added a set of strings to it:

Expand|Select|Wrap|Line Numbers
  1. DataSet ds = new DataSet();
  2. DataTable dt = new DataTable("table");
  3. ds.Tables.Add(dt);
  4. dt.Columns.Add("id");
  5. dt.Columns.Add("description");
  6. dt.Columns.Add("price");
  7.  
  8. for (int i = 0; i < Data.Count; i++)
  9. {
  10. string id = sourceofdata[i].id  //Here is the main problem ** needs to be a cell item
  11.  
  12. string description = sourceofdata[i].description
  13. }
  14.  
  15. DataList1.Datasource = ds;
  16. DataList1.DataBind();
Sep 1 '08 #1
3 1777
vekipeki
229 Expert 100+
Use the DataTable.NewRow() method to get a new row instance for that table, then set the individual columns for that row, something like this:

Expand|Select|Wrap|Line Numbers
  1. for (int i = 0; i < sourceOfData.Length; i++)
  2. {
  3.     DataRow dRow = dt.NewRow();
  4.     dRow["id"] = sourceOfData[i].Id;
  5.     dRow["description"] = sourceOfData[i].Desc;
  6.     dRow["price"] = sourceOfData[i].Price;
  7.     dt.Rows.Add(dRow);
  8. }
  9.  
  10. dataList.DataSource = dt; // bind to a table
  11.  
Sep 1 '08 #2
If sourceofdata is another table that looks the same you can use:

Expand|Select|Wrap|Line Numbers
  1. foreach (DataRow dr in sourceofdata.Rows)
  2. {
  3. ...
  4. }
if it's another DataSet:
Expand|Select|Wrap|Line Numbers
  1. foreach (DataRow dr in sourceofdata.Tables[0].Rows)
  2. {
  3. ...
  4. }
Change 0 to the index you want or the name of the table as string.
Sep 1 '08 #3
Hi did anyone have any problem using this code?

for (int i = 0; i < sourceOfData.Length; i++)
{
DataRow dRow = dt.NewRow();
dRow["id"] = sourceOfData[i].Id;
dRow["description"] = sourceOfData[i].Desc;
dRow["price"] = sourceOfData[i].Price;
dt.Rows.Add(dRow);
}

Everytime I use this, the first dRow does not have any data, it's all null. But then the next time this executes "dt.Rows.Add(dRow); ", the one being inserted is the last dRow which is in i-1. So when I have 5 dRows, the first one is empty then then I'm not getting the last dRow.

I followed pretty much the exact code just the naming is different. What am I doing wrong?
Jun 30 '09 #4

Post your reply

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

Similar topics

3 posts views Thread by Jim Heavey | last post: by
2 posts views Thread by dSchwartz | last post: by
10 posts views Thread by Trevor | last post: by
4 posts views Thread by igotyourdotnet | last post: by
6 posts views Thread by Lord Zoltar | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.