例外:输入数组输入数组长于此表组合框中的列数

时间:2018-03-13 08:51:23

标签: c# arrays datatable combobox static-methods

为了解释我在做什么,我尝试将特定列中的数据加载到组合框中,我使用静态方法。异常跳出下面代码的 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;
    }
}

我做错了什么?我该怎么办呢?参考就够了吗?

1 个答案:

答案 0 :(得分: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;