【问题标题】:Index Out of Range exception visual studio索引超出范围异常视觉工作室
【发布时间】:2013-02-21 13:34:14
【问题描述】:

在我的 winform 中,我试图通过传递商品的名称从数据库中获取商品的价格。 用户可以在从数据库中填充项目的组合框中看到项目。 当用户从组合框中选择项目并单击添加时,它将该特定项目添加到数据库中。

在用户添加商品的同时,其中一个文本框添加了价格。如果用户添加五个项目,则文本框显示五个项目价格的总和。到这里一切正常。

现在,当用户想要从列表框中删除项目时,用户选择该项目并单击删除项目,Visual Studio 会抛出错误“索引超出范围”。

我使用相同的代码来获取 add 方法和 substract 方法的价格,但不确定为什么只有 add 方法有效,而 substract 无效

添加价格的代码

public int addPrice()
        {

            DataSet ds = searchforPrice(comboBox2.Text);
            int sum;
            bool success = int.TryParse(maskedTextBox10.Text, out sum);
            int price = Convert.ToInt32(ds.Tables[0].Rows[0]["Price"]);
            return sum + price;

        }

减价代码

 public int subPrice()
        {

            DataSet ds = searchforPrice(listBox1.GetItemText(listBox1.SelectedItem));
            int sum;
            bool success = int.TryParse(maskedTextBox10.Text, out sum);
            int price = Convert.ToInt32(ds.Tables[0].Rows[0]["Price"]);
            return sum - price;

        }

从数据库中获取价格的代码

public DataSet searchforPrice(string itemName)
{
    DataSet dataSet = new DataSet();

    // Create connection object
    OleDbConnection oleConn = new OleDbConnection(connString);
    try
    {
        oleConn.Open();
        string sql = "SELECT [Price]  FROM [Product] WHERE [Product Name] ='" + itemName + "'";
        OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, oleConn);
        dataAdapter.Fill(dataSet, "Product");

    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
    finally
    {
        oleConn.Close();
    }
    return dataSet;
}

【问题讨论】:

  • 在这种情况下,这意味着您的表是空的。帮自己一个忙,看看参数化查询。
  • 在代码中放一个断点,看看你在哪里得到了异常。如果您的索引超出范围,这往往意味着您正在访问一个数字大于长度的数组。
  • listBox1.GetItemText(listBox1.SelectedItem) 为 null 不知道为什么
  • 注意我认为你的问题是 listBox.GetItemText(listbox.SelectedItem)。为什么不使用它来代替 ListBox1.SelectedValue.ToString();

标签: c# winforms listbox


【解决方案1】:

您的结果集中要么没有表,要么没有行。这意味着访问第一个条目(索引 0)将不起作用,因为没有第一个条目。你会得到一个IndexOutOfRangeException。检查您的请求和数据源。

【讨论】:

  • 但它完美地适用于添加方法,为什么不适用于减法,因为我将项目名称作为两个方法的字符串传递
【解决方案2】:

这失败了,因为searchForPrice 没有返回表中的任何行。因此错误

位置 0 处没有行。

因此,如果您更改行以从列表框或表单上的其他位置获取值,这将返回数据,您的错误将得到修复。

真正的根本问题是传递给searchForPrice 的值。

【讨论】:

    【解决方案3】:

    方法 searchforPrice 返回一个没有行的数据集。因此,Rows[0] 不存在。检查您的方法并使其适应 searchforPrice 未返回数据(未找到任何价格)的情况。

    if (ds.Tables[0].Rows.Count != 0
    

    { ...}

    【讨论】:

      【解决方案4】:

      问题是因为您的数据集返回 0 行。那是因为项目名称没有传递给 SQL 查询。 您只需要对 subPrice() 函数进行细微更改,

      public int subPrice()
              {
      
                  DataSet ds = searchforPrice(listBox1.SelectedItem.ToString());
                  int sum;
                  bool success = int.TryParse(maskedTextBox10.Text, out sum);
                  int price = Convert.ToInt32(ds.Tables[0].Rows[0]["Price"]);
                  return sum - price;
      
              }
      

      【讨论】:

      • Visual Studio 无法识别 ListBoxItem
      • 直接使用 listBox1.SelectedValue.ToString 即可。如果所选项目是复杂对象,则可以执行 ((CAST)ListBox.SelectedItem).THE_PROPERTY_YOU_NEED。
      • @Amrit 如果我是你,我会设置一个断点并在快速观察窗口中查看 listbox.selectedItem 和 selectedvalue 是什么。我们为您提供的方案应该可行,如果它们不是,那么前进的唯一方法就是看看您从这些财产中得到了什么。
      【解决方案5】:

      提供的代码应该可以工作。

      您需要检查实际数据源中的列是否与通过 ListBox 项传递的列相匹配。在我看来,您的命名约定很可能存在差异。

      如果通过 ListBox 传递的列名与您的数据源中的列名匹配,则以下代码应该可以工作:-

      public int subPrice()
              {
                  if (listBox1.SelectedItems.Count > 0)
                  {
                      string SearchString = listBox1.SelectedItem.ToString().Trim();
                      DataSet ds = searchforPrice(SearchString);
      
                      if (ds.Tables["Product"].Rows.Count > 0)
                      {
                          bool success = int.TryParse(maskedTextBox10.Text, out sum);
                          int price = Convert.ToInt32(ds.Tables["Product"].Rows[0]["Price"]);
                          return sum - price;
                      }                
                  }
      
                return null;
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-16
        • 1970-01-01
        • 1970-01-01
        • 2011-12-25
        • 2023-04-10
        相关资源
        最近更新 更多