Search code examples
c#datatabledatasourcerepeater

c# Randomize DataTable rows


I have a Data Table I'm using as the data source for a repeater and would like to have the results show in a random order each time it's called.

I've been able to do this while retrieving the data but wish to cache the result set before it's bound.

Is the any was to shuffle or randomise the rows of a data table before binding to the repeater?

CODE:

        TreeProvider tp = new TreeProvider();
    DataSet ds = new DataSet();
    string sKey = "KEY";
    using (CachedSection<DataSet> cs = new CachedSection<DataSet>(ref ds, 5, true, null, sKey))
    {
      if (cs.LoadData)
      {
        ds = tp.SelectNodes("", "URL", "", true, "DOCTYPE", "", "NewID()", -1, true, 5);
        cs.Data = ds;
      }
    }
    if (!DataHelper.DataSourceIsEmpty(ds))
    {
      rprItems.DataSource = ds.Tables[0].DefaultView;
      rprItems.DataBind();
    }

Any guidance is appreciated.


Solution

  • I ended up taking a copy of the table, adding a field and assigning a random number to each row then ordering by that row.

            DataTable dt = ds.Tables[0].Copy();
            if (!dt.Columns.Contains("SortBy"))
              dt.Columns.Add("SortBy", typeof (Int32));
    
            foreach (DataColumn col in dt.Columns)
              col.ReadOnly = false;
    
            Random rnd = new Random();
            foreach (DataRow row in dt.Rows)
            {
              row["SortBy"] = rnd.Next(1, 100);
            }
            DataView dv = dt.DefaultView;
            dv.Sort = "SortBy";
            DataTable sortedDT = dv.ToTable();
    
            rprItems.DataSource = sortedDT;
            rprItems.DataBind();