實現效果:

知識運用:
Array對象的Length屬性 int類的tryParse()方法
實現代碼:
int[] int_arr;
//"隨機數組"按鈕事件
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.Clear(); //清掉多余內容
int_arr = new int[10];
label1.Text = "";
for (int i = 0; i < 10;i++ ){
int_arr[i]=(new Random()).Next(0,9);
System.Threading.Thread.Sleep(30); //添加休眠 避免數字相同
label1.Text += int_arr[i] + " ";
}
}
//"添加"按鈕事件
private void button2_Click(object sender, EventArgs e)
{ int site,value;
if ((label1.Text != string.Empty) && (int.TryParse(textBox1.Text, out site)) &&
(int.TryParse(textBox2.Text, out value))) //進行了安全設置
{
foreach(int i in AddArray(int_arr,int.Parse(textBox1.Text),int.Parse(textBox2.Text))){
richTextBox1.Text += i + " ";
}
}
else { MessageBox.Show("請填寫完整"); }
}
//定義插入的方法
public int[] AddArray(int[] ArrayBorn,int Index,int Value) {
if (Index >= ArrayBorn.Length) //判斷索引大於等於數組長度
Index = ArrayBorn.Length; //設置索引長度為數組長度
int[] temArray=new int[ArrayBorn.Length+1]; //創建插入后的新數組
for (int i = 0; i < temArray.Length;i++ ) //遍歷新數組
{
if (Index >= 0) //索引大於等於零
{
if (i < Index )
temArray[i] = ArrayBorn[i];
else if (i == Index)
temArray[i] = Value;
else
temArray[i] = ArrayBorn[i - 1];
}
else { //索引小於零
if (i == 0)
temArray[i] = Value; //添加值在首位
else
temArray[i] = ArrayBorn[i - 1];
}
}
return temArray;
}
