索引超出数据集范围,但sql语句是正确的

时间:2014-08-25 10:41:19

标签: c# sql sql-server winforms dataset

我有一个用我的数据库填充数据的combox框,我在表单的构造函数中调用FillCombos函数。

//Variables of class

 DataSet ds = new DataSet();
 DataTools mytool = new DataTools();

private void FillCombos()
    {
        string cmd = "";

        //Llena cmb Categoria
        ds.Clear();
        cmd = "select descripcion from Categoria";
        ds = mytool.Execute(cmd);

        if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        {
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                this.cmbCategoria.Items.AddRange(new object[] 
                  {
                    ds.Tables[0].Rows[i]["descripcion"].ToString()});
        }
        ds.Clear();
     }

然后当用户选择我想要显示子类别的类别时。所以我有这个 方法

private void cmbCategoria_SelectedIndexChanged(object sender, EventArgs e)
    {
        //ds.Clear();
        string cmd = "select Categoria.cod_cat from Categoria where Categoria.descripcion = '" + cmbCategoria.Text + "'";
        ds = mytool.Execute(cmd);

    //Keeps telling me that is out of range here is the problem
        MessageBox.Show(ds.Tables[0].Rows[0][0].ToString());
        if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        {
            MessageBox.Show(cmd);
            MessageBox.Show(ds.Tables[0].Rows[0][0].ToString());
        }
       // codCat = Convert.ToInt32(ds.Tables[0].Rows[0]["cod_cat"].ToString());
        ds.Clear();

        cmd = "select descripcion  from SubCategoria where cod_cat = " + codCat.ToString();
        ds = mytool.Execute(cmd);

        this.cmbSubCategoria.Items.Clear();
        if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        {
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                this.cmbSubCategoria.Items.AddRange(new object[] 
                  {
                    ds.Tables[0].Rows[i]["descripcion"].ToString()});
        }
        ds.Clear();
    }

我的问题是,visual studio告诉我数据集超出范围,但我尝试了 在sql中的句子,它返回一个带有一行和一列的id,所以为什么索引超出范围的消息,为什么sql语句没有正确执行。

我在地址表单中使用了相同的代码并且运行正常。 我尝试更改数据集,另一个数据集与另一个数据集,放置一个静态SQL查询,但似乎没有任何工作。

1 个答案:

答案 0 :(得分:0)

由于cmbCategoria.Text不包含预期值,因此SELECT语句很可能无法返回结果。请在执行SELECT语句之前停止你的pgm,并查看cmbCategoria.Text的内容

更新:请改为尝试 string cmd = "select Categoria.cod_cat from Categoria where Categoria.descripcion = '" + cmbCategoria.SelectedItem.ToString() + "'";

此处有更多信息:Combobox.Text Vs combobox.Selecteditem Vs combobox.selectValue?