c#想在toolstrip中插入datetimepicker控件,但是试了下面的方法不行,不知道什么原因

    private void AddDTPtoToolstrip(int n)
    {
        DateTimePicker dtp = new DateTimePicker();
        dtp.Width = 110;
        dtp.Format = DateTimePickerFormat.Custom;
        ToolStripControlHost host1 = new ToolStripControlHost(dtp);
        toolStrip1.Items.Insert(n, host1);//提示这句话索引已超出范围
    }

在Load事件中调用上面的代码,提示 :其他信息: 插入索引已超出范围。必须为非负值,并且必须小于或等于大小。

应该是你传入的参数n的值超过了toolStrip1.Items这个集合的长度,比如下面示例:

using System;
using System.Collections.Generic;

namespace ConsoleApp2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var list = new List<int> { 1, 2, 3, 4, 5 };
            // 在索引为0的位置插入数字6
            list.Insert(0, 6);
            // 输出插入后的结果
            Console.WriteLine(string.Join(",", list));

            list = new List<int> { 1, 2, 3, 4, 5 };
            // 在索引为3的位置插入数字6
            list.Insert(3, 6);
            // 输出插入后的结果
            Console.WriteLine(string.Join(",", list));

            list = new List<int> { 1, 2, 3, 4, 5 };
            // 在索引为5的位置插入数字6
            list.Insert(5, 6);
            // 输出插入后的结果
            Console.WriteLine(string.Join(",", list));

            //list = new List<int> { 1, 2, 3, 4, 5 };
            //// 在索引为3的位置插入数字6
            //list.Insert(6, 6);
            //// 输出插入后的结果
            //Console.WriteLine(string.Join(",", list));

            Console.ReadKey();
        }
    }
}

输出结果:

using System;
using System.Collections.Generic;

namespace ConsoleApp2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var list = new List<int> { 1, 2, 3, 4, 5 };
            // 在索引为0的位置插入数字6
            list.Insert(0, 6);
            // 输出插入后的结果
            Console.WriteLine(string.Join(",", list));

            list = new List<int> { 1, 2, 3, 4, 5 };
            // 在索引为3的位置插入数字6
            list.Insert(3, 6);
            // 输出插入后的结果
            Console.WriteLine(string.Join(",", list));

            list = new List<int> { 1, 2, 3, 4, 5 };
            // 在索引为5的位置插入数字6
            list.Insert(5, 6);
            // 输出插入后的结果
            Console.WriteLine(string.Join(",", list));

            Console.ReadKey();
        }
    }
}

如果使用如下示例的Insert(索引超过了数组索引长度),则会抛出异常:

var list = new List<int> { 1, 2, 3, 4, 5 };

// 在索引为6的位置插入数字6
list.Insert(6, 6);
// 输出插入后的结果
Console.WriteLine(string.Join(",", list));

异常如下图:

img