Reputation: 3057
Ho do I go about adding random minutes to column in dataset, here is my code:
protected void btnUpdateTable_Click(object sender, EventArgs e)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
///check if column[logout] is null or empty, fill it
if(dr.IsNull("logout_time"))
{
///get the login colum datetime
/// add random datetime to it
if (!dr.IsNull("login_time"))
{
DateTime dt = Convert.ToDateTime(dr["login_time"]);
dt = dt.AddMinutes(?);/// "?"<--here I want to add random minutes
}
}
}
Any help greatly appreciated.
Thank you all for the help, here my final Code snippet:
foreach (DataRow dr in ds.Tables[0].Rows)
{
///check if column[logout] is null or empty, fill it
if(dr.IsNull("logout_time"))
{
///get the login colum datetime
/// add random datetime to it
if (!dr.IsNull("login_time"))
{
DateTime dt = Convert.ToDateTime(dr["login_time"]);
Random rand = new Random();
//return random.Next(0, 59);
dt = dt.AddMinutes(rand.Next(0,59));
dt = dt.AddSeconds(rand.Next(0, 59));
dr["logout_time"] = dt;
}
}
}
Upvotes: 1
Views: 1210
Reputation: 128357
Assuming you don't want your dt object to get moved into the next hour (e.g., you would want any time between 8:00 and 8:59 to get moved up to 8:59 at most), I would suggest making the following changes:
protected void btnUpdateTable_Click(object sender, EventArgs e)
{
Random rand = new Random;
foreach (DataRow dr in ds.Tables[0].Rows)
{
///check if column[logout] is null or empty, fill it
if(dr.IsNull("logout_time"))
{
///get the login colum datetime
/// add random datetime to it
if (!dr.IsNull("login_time"))
{
DateTime dt = Convert.ToDateTime(dr["login_time"]);
dt = dt.AddMinutes(rand.Next(0, (60 - dt.Minutes)));
}
}
}
}
Upvotes: 3
Reputation: 3685
Try using Random
:
Random randGen = new Random();
foreach (DataRow dr in ds.Tables[0].Rows)
{
///check if column[logout] is null or empty, fill it
if(dr.IsNull("logout_time"))
{
///get the login colum datetime
/// add random datetime to it
if (!dr.IsNull("login_time"))
{
DateTime dt = Convert.ToDateTime(dr["login_time"]);
dt = dt.AddMinutes(randGen.Next(0, 60));
/// "?"<--here I want to add random minutes
}
}
}
Upvotes: 7
Reputation: 115508
You can use this:
Random random = new Random();
foreach(DataRow dr ...)
{
int rand = random.Next(0, 60);
}
As a comment pointed out, you don't need to create a new Random object for every number you wish to create. (Actually, you probably shouldn't).
Upvotes: 12
Reputation: 19263
Also please note that two if-statements within each other can be optimized to:
protected void btnUpdateTable_Click(object sender, EventArgs e) {
foreach (DataRow dr in ds.Tables[0].Rows)
if(dr.IsNull("logout_time") && !dr.IsNull("login_time")) {
DateTime loginTime = Convert.ToDateTime(dr["login_time"]);
loginTime = loginTime.AddMinutes(new Random().Next(0,59));
}
}
Upvotes: 0