【问题标题】:Exception:Input array Input array is longer than the number of columns in this table combobox异常:输入数组输入数组长于此表组合框中的列数
【发布时间】:2018-08-21 10:50:54
【问题描述】:

为了解释我在做什么,我尝试将特定列中的数据加载到组合框中,为此我使用静态方法。异常跳出以下代码的 7 行。每当我运行程序时,这行就会抛出异常,输入数组输入数组比这个表中的列数长。

void DataGridViewModules()
{
    DataRow dr;
    CommonDBTransaction c = new CommonDBTransaction();
    string sql = "SELECT MId FROM Module";
    DataTable dt = c.searchData(sql);
    dr = dt.NewRow();
    dr.ItemArray = new object[] { 0, "--Select Module--" }; //Exception jumps out here
    dt.Rows.InsertAt(dr,0);
    metroComboBoxMod.ValueMember = "MId";
    metroComboBoxMod.DisplayMember = "MId";
    metroComboBoxMod.DataSource = dt;
}

用于查询数据的静态方法是,

public DataTable searchData(string query)
{
    try
    {
        DataTable table = new DataTable();
        using(SqlConnection con = new SqlConnection(....constring here...))//connection string was added
        {
            using(SqlDataAdapter da = new SqlDataAdapter(query, con))
               da.Fill(table);
        }
        return table;
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.ToString());
        return null;
    }
}

我做错了什么?我该如何解决它&参考就足够了?

【问题讨论】:

  • 这是异常的真实复制/粘贴吗?
  • @Rafalon 是的
  • @Alexey 和接受他/她编辑的人,请小心,因为代码格式实际上改变了行数,因此 line 9 的位置
  • @Rafalon 明白了,我的错
  • @MRDR 不提供行号,为什么不在代码中添加注释in 类似// <-- exception thrown here 这样就不会有任何混淆?

标签: c# arrays datatable combobox static-methods


【解决方案1】:

看起来您只在选择查询中检索一列,但您正在向新行添加一个 2 列数组。

你也许可以摆脱以下:

DataRow dr;
CommonDBTransaction c = new CommonDBTransaction();
string sql = "SELECT MId FROM Module";
DataTable dt = c.searchData(sql);
dr = dt.NewRow();
dr[0] = "--Select Module--";
dt.Rows.InsertAt(dr,0);
metroComboBoxMod.ValueMember = "MId";
metroComboBoxMod.DisplayMember = "MId";
metroComboBoxMod.DataSource = dt;

否则,您可能需要为 ValueMember 和 DisplayMember 设置一个单独的列:

DataRow dr;
CommonDBTransaction c = new CommonDBTransaction();
string sql = "SELECT MId AS MId, MId AS DisplayId FROM Module";
DataTable dt = c.searchData(sql);
dr = dt.NewRow();
dr[0] = 0;
dr[1] = "--Select Module--";
dt.Rows.InsertAt(dr,0);
metroComboBoxMod.ValueMember = "MId";
metroComboBoxMod.DisplayMember = "DisplayId";
metroComboBoxMod.DataSource = dt;

【讨论】:

  • 删除 dr.ItemArray = new object[] {"--Select Module--" }; //异常跳出这里就像一个魅力感谢@qwertydog!
  • 没问题,如果显示不正确,请查看编辑
  • 就像刚刚测试过的魅力一样工作。再次感谢!
猜你喜欢
  • 2019-03-27
  • 2023-03-11
  • 2017-09-03
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
  • 1970-01-01
  • 2015-06-02
相关资源
最近更新 更多