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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dmj07
    New Member
    • Aug 2008
    • 55

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

    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:

    Code:
    DataSet ds = new DataSet();
    DataTable dt = new DataTable("table");
    ds.Tables.Add(dt);
    dt.Columns.Add("id");
    dt.Columns.Add("description");
    dt.Columns.Add("price");
    
    for (int i = 0; i < Data.Count; i++)
    {
    string id = sourceofdata[i].id  //Here is the main problem ** needs to be a cell item
            
    string description = sourceofdata[i].description
    }
    
    DataList1.Datasource = ds;
    DataList1.DataBind();
    Last edited by dmj07; Sep 1 '08, 01:29 PM. Reason: Code tags
  • vekipeki
    Recognized Expert New Member
    • Nov 2007
    • 229

    #2
    Use the DataTable.NewRo w() method to get a new row instance for that table, then set the individual columns for that row, something like this:

    [CODE=C#]
    for (int i = 0; i < sourceOfData.Le ngth; i++)
    {
    DataRow dRow = dt.NewRow();
    dRow["id"] = sourceOfData[i].Id;
    dRow["descriptio n"] = sourceOfData[i].Desc;
    dRow["price"] = sourceOfData[i].Price;
    dt.Rows.Add(dRo w);
    }

    dataList.DataSo urce = dt; // bind to a table
    [/CODE]

    Comment

    • DonBytes
      New Member
      • Aug 2008
      • 25

      #3
      If sourceofdata is another table that looks the same you can use:

      Code:
      foreach (DataRow dr in sourceofdata.Rows)
      {
      ...
      }
      if it's another DataSet:
      Code:
      foreach (DataRow dr in sourceofdata.Tables[0].Rows)
      {
      ...
      }
      Change 0 to the index you want or the name of the table as string.
      Last edited by DonBytes; Sep 1 '08, 07:55 PM. Reason: Misstype

      Comment

      • jcatubay
        New Member
        • Mar 2007
        • 12

        #4
        Hi did anyone have any problem using this code?

        for (int i = 0; i < sourceOfData.Le ngth; i++)
        {
        DataRow dRow = dt.NewRow();
        dRow["id"] = sourceOfData[i].Id;
        dRow["descriptio n"] = sourceOfData[i].Desc;
        dRow["price"] = sourceOfData[i].Price;
        dt.Rows.Add(dRo w);
        }

        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(dR ow); ", 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?

        Comment

        Working...