C#程序設計(十九)----10個隨機數在列表框中顯示出來

* 程序的版權和版本聲明部分
* Copyright (c) 2012, 煙臺大學計算機學院學生
* All rights reserved.

* 作 者: 劉鎮
* 完成日期: 2012 年 11 月 10 日
* 版 本 號: 3.019

* 對任務及求解方法的描述部分

* 問題描述:利用Random類產生10個[10,99]之間的隨機數,並將這10個隨機數在列表框中顯示出來,每個數佔一項。用戶選擇某項後,在右邊標籤中顯示所選內容。

 

*代碼部分:

 

 

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace win7
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Hashtable hashtable = new Hashtable();
            Random random = new Random();

            for (int i = 0; hashtable.Count < 10; i++)
            {
                int value = random.Next(10, 100);
                if (!hashtable.ContainsValue(value) && value != 0)
                {
                    hashtable.Add(value, value);
                    listBox1.Items.Add(value.ToString());
                }
            } 
        }

        private void listBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            label1.Text = listBox1.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close(); 
        }
    }
}


 

 

測試結果:

 

 

 

心得經驗:

 

一、用一個小循環輸出十個隨機數,作爲ListBox的選項;

二、關鍵是怎樣實現十個數不重複:解決方案我還是覺得這篇博文中解釋的比較好:http://www.cnblogs.com/falla/archive/2010/01/29/1659399.html

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章