开发者

textbox random line selection c#

lets say I have a multi-line textbox with 100 lines, how would you go about selecting one 开发者_如何学JAVAof those lines randomly in c# and putting that value in a string.


Random r = new Random();
int index = r.Next(0, textBox1.Lines.Length);
string line = textBox1.Lines[index];

Of course r should be a class or instance variable and not re-newed every time you need this, otherwise it won't be so random.

Edit per comment:

This uses the Random.Next() overload that allows you to specify a range from which you want to pick a (pseudo-) random number. The 0 is the inclusive lower bound of the range, textBox1.Lines.Length is the exclusive upper bound of the range (which means that that number itself won't be part of the range) - so you will get numbers from 0 to textBox1.Lines.Length -1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜