何我要在数据集中向列中添加随机分钟,这是我的代码:
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 } } }
任何帮助非常感谢.
谢谢大家的帮助,这是我的最终代码片段:
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; } } }
kemiller2002.. 12
你可以用这个:
Random random = new Random(); foreach(DataRow dr ...) { int rand = random.Next(0, 60); }
正如评论指出的那样,您不需要为要创建的每个数字创建新的Random对象.(实际上,你可能不应该).
你可以用这个:
Random random = new Random(); foreach(DataRow dr ...) { int rand = random.Next(0, 60); }
正如评论指出的那样,您不需要为要创建的每个数字创建新的Random对象.(实际上,你可能不应该).
尝试使用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 } } }