【问题标题】:Input array length is longer than the number of columns in datatable输入数组长度大于数据表中的列数
【发布时间】:2019-11-19 21:33:22
【问题描述】:

我用datagridview 创建了一个windows 窗体。我创建了以下代码来创建表并加载用户输入。我不断收到错误输入数组比列数长。不知道怎么做?因为我已经设置了列构建。

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

namespace WindowsFormsApp17
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        DataTable table = new DataTable();

        private void Add_Row_To_DataGridView_Using_TextBoxes_Load(object sender, EventArgs e)
        {
            // set datatable columns values
            DataTable Test = new DataTable();
            table.Columns.Add("Id", typeof(int));// data type int
            table.Columns.Add("First Name", typeof(string));// datatype string
            table.Columns.Add("Last Name", typeof(string));// datatype string
            table.Columns.Add("Age", typeof(int));// data type int

            dataGridView1.DataSource = table;
        }


        private void button1_Click(object sender, EventArgs e)
        {
            table.Rows.Add(textBoxID.Text, textBoxFN.Text, textBoxLN.Text, textBoxAGE.Text);
            dataGridView1.DataSource = table;
        }
    }
}

【问题讨论】:

  • 你从哪里得到这个数组(至极线)?还请提供异常的类型、消息和理想情况下的堆栈跟踪。
  • Add_Row_To_DataGridView_Using_TextBoxes_Load 在哪里调用?您正在尝试在设置列之前向表中添加一行。
  • 为什么要声明数据类型为 int 的列,然后为它们分配字符串值? (这与您收到的错误无关)
  • @Christopher DataRowCollection.Add(object[]) 在数组中值的数量超过表中的列数时抛出此异常。
  • @Amy,谢谢,不确定这是不是最好的方法,但我能够在添加行之前将添加列移动到按钮单击事件中并且它起作用了。

标签: c# datatable


【解决方案1】:

您的Add_Row_To_DataGridView_Using_TextBoxes_Load 方法没有被执行。

转到表单的属性选项卡,选择事件选项卡,然后将方法名称与Load 事件放在一起。

【讨论】:

  • 将方法重命名为 Form1_Load 也可能有效。
猜你喜欢
  • 2019-03-27
  • 2018-08-21
  • 2017-09-03
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 2019-07-09
相关资源
最近更新 更多