如下图所示,随机生成多个 不重复 的随机数(整数,100以下),个数可以通过对话框窗口获取;生成数据后,按 降序 将其显示在ListBox控件中(每次只能选择一项),按钮Up和Down分别上调和下调选择项;
![]()
思路:
- 在对话框Form2中
定义一个属性Number;
public int Number { get; set; }
在确定按钮中,
this.Numbert = int.Parse(this.textBox1.Text);
this.DialogResult = DialogResult.OK;
- 在窗体Form1的代码中,访问窗体对象form2.Number;
下面贴上代码:
1Form1 :
public partial class Form1 : Form
{
private List <int>
a = new List <int>();
private HashSet <int>
hs = new HashSet <int>();
public Form1()
{
InitializeComponent();
}
private void btnGenerate_Click(object sender, EventArgs e)
{
//清空列表,在列表中显示生成的随机数
for( int i
= listBox1.Items.Count-1; i>=0 ;i--)
{
listBox1.Items.RemoveAt(i);
}
//清空HashSet
hs.Clear();
int count=0;
try //获取生成个数
{
count = Int32.Parse(textCount.Text);
}
catch (Exception ex)
{
MessageBox.Show("个数有误" );
}
Random r
= new Random(( int)DateTime .Now.Ticks);
//以当前时间为时间随机种子
//生成随机数
for (int i
= 0; hs.Count< count; i++)
{
hs.Add(r.Next(100));
}
a=hs.ToList< int>();
//HashSet转为List
a.Sort(); // 排序
//输出随机数到列表
for (int i
= 0; i <a.Count; i++)
{
this.listBox1.Items.Add(a[i]);
}
}
//选?中的元素上升
private void btnUp_Click(object sender, EventArgs e)
{
int index
= this .listBox1.SelectedIndex;
if (index
> 0)
{
listBox1.Items.Insert(index-1,listBox1.SelectedItem);
listBox1.Items.RemoveAt(index+1);
}
}
//选中的元素下降
private void btnDown_Click(object sender, EventArgs e)
{
int index
= this .listBox1.SelectedIndex;
if (index
>=0 && index< listBox1.Items.Count-1)
{
listBox1.Items.Insert(index + 2, listBox1.SelectedItem);
listBox1.Items.RemoveAt(index);
}
}
// 获得其他对话框的值
private void btnGet_Click(object sender, EventArgs e)
{
Form2 f
= new Form2();
f.ShowDialog(); //关键,不可用Show
if (f.DialogResult
== DialogResult .OK)
{
this.textCount.Text
= Convert .ToString(f.number);
}
}
}
2、 Form2
public partial class Form2 : Form
{
public int number
{ get; set ;
} //关键
public Form2()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{
try
{
this .number
= int .Parse( this.textBox1.Text);
//关键
this .DialogResult
= DialogResult .OK; //关键
}
catch {
MessageBox .Show("请?输??入??正y确???数?y字??!??" );
}
}
private void button2_Click( object sender, EventArgs e)
{
this .DialogResult
= DialogResult .Cancel;
}
}