【问题标题】:Index (zero based) must be greater than or equal to zero and less than the size of the argument list while inserting the arraylist插入数组列表时,索引(从零开始)必须大于或等于零且小于参数列表的大小
【发布时间】:2025-12-26 11:45:16
【问题描述】:

我收到此错误:

索引(从零开始)必须大于或等于零且小于参数列表的大小。

在这里:

splitItems = item.Split(",".ToCharArray()); 

sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ",
      ds.InsertPlan("1", splitItems[0], splitItems[1], splitItems[2],
                    splitItems[3], DateTime.Now, DateTime.Now, user, user, "Nil", 1));

C#代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections.Specialized;
using System.Text;

public partial class Site_Allocation_Plan_Entry : System.Web.UI.Page
{
    private void SetInitialRowToGrid()
    {
        // Initialize and Set initial row of Datatable
        var tempDataTable = new DataTable();
        tempDataTable.Columns.Add("txtDate1");
        tempDataTable.Columns.Add("txtPlace1");
        tempDataTable.Columns.Add("txtPlace2");
        tempDataTable.Columns.Add("txtDistance");
        tempDataTable.Rows.Add("1", "", "", "");

        // Store that datatable into viewstate
        ViewState["TempTable"] = tempDataTable;

        // Attach Gridview Datasource to datatable
        GridView1.DataSource = tempDataTable;
        GridView1.DataBind();
    }

    private void AddNewRowToGrid()
    {
        int rowIndex = 0;

        if (ViewState["TempTable"] != null)
        {
            // Get TempTable from viewstate
            var tempTable = (DataTable)ViewState["TempTable"];
            DataRow tempRow = null;

            if (tempTable.Rows.Count > 0)
            {
                for (int i = 1; i <= tempTable.Rows.Count; i++)
                {
                    // Get Grid's TextBox values
                    var dateText =
                        (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtDate1");
                    var place1Text =
                        (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace1");
                    var place2Text =
                        (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace2");
                    var distanceText =
                        (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtDistance");

                    // Create new row and update Row Number
                    tempRow = tempTable.NewRow();

                    tempTable.Rows[i - 1]["txtDate1"] = dateText.Text;
                    tempTable.Rows[i - 1]["txtPlace1"] = place1Text.Text;
                    tempTable.Rows[i - 1]["txtPlace2"] = place2Text.Text;
                    tempTable.Rows[i - 1]["txtDistance"] = distanceText.Text;

                    rowIndex++;
                }

                // Add data to datatable and viewstate
                tempTable.Rows.Add(tempRow);
                ViewState["TempTable"] = tempTable;

                // Attach Gridview Datasource to datatable
                GridView1.DataSource = tempTable;
                GridView1.DataBind();
            }
        }

        //Set Previous Data on Postbacks
        SetPreviousData();
    }

    private void SetPreviousData()
    {
        int rowIndex = 0;

        if (ViewState["TempTable"] != null)
        {
            var tempTable = (DataTable)ViewState["TempTable"];

            if (tempTable.Rows.Count > 0)
            {
                for (int i = 0; i < tempTable.Rows.Count; i++)
                {
                    var dateText =
                        (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtDate1");
                    var place1Text =
                        (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace1");
                    var place2Text =
                        (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("txtPlace2");
                    var distanceText =
                        (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("txtDistance");

                    dateText.Text = tempTable.Rows[i]["txtDate1"].ToString();
                    place1Text.Text = tempTable.Rows[i]["txtPlace1"].ToString();
                    place2Text.Text = tempTable.Rows[i]["txtPlace2"].ToString();
                    distanceText.Text = tempTable.Rows[i]["txtDistance"].ToString();

                    rowIndex++;
                }
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.SetInitialRowToGrid();
        }
    }

    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        AddNewRowToGrid();
    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        int index = Convert.ToInt32(e.RowIndex);

        deleteRow(index);
        SetPreviousData();
    }
    private int deleteRow(int index)
    {
        int rowIndex = 0;

        if (ViewState["TempTable"] != null)
        {
            // Get TempTable from viewstate
            var tempTable = (DataTable)ViewState["TempTable"];


            if (tempTable.Rows.Count > 0)
            {
                for (int i = 1; i <= tempTable.Rows.Count; i++)
                {
                    // Get Grid's TextBox values
                    var dateText =
                        (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtDate1");
                    var place1Text =
                        (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace1");
                    var place2Text =
                        (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace2");
                    var distanceText =
                        (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtDistance");                    
                }

                // Add data to datatable and viewstate                
                tempTable.Rows.RemoveAt(index);
                ViewState["TempTable"] = tempTable;

                // Attach Gridview Datasource to datatable
                GridView1.DataSource = tempTable;
                GridView1.DataBind();
            }
        }

        //Set Previous Data on Postbacks        
        return index;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        int rowIndex = 0;
        StringCollection sc = new StringCollection();
        if (ViewState["TempTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["TempTable"];
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    //extract the TextBox values
                    TextBox box1 = (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace1");
                    TextBox box2 = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("txtPlace2");
                    TextBox box3 = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("txtDistance");
                    TextBox box4 = (TextBox)GridView1.Rows[rowIndex].Cells[4].FindControl("txtDate1");

                    //get the values from the TextBoxes
                    //then add it to the collections with a comma "," as the delimited values
                    sc.Add(box1.Text + "," + box2.Text + "," + box3.Text + "," + box4.Text);
                    rowIndex++;
                }
                //Call the method for executing inserts
                InsertRecords(sc);
            }
        }
    }
    private void InsertRecords(StringCollection sc)
    {
        DS_SiteDataTableAdapters.tbl_planTableAdapter ds;
        ds = new DS_SiteDataTableAdapters.tbl_planTableAdapter();

        StringBuilder sb = new StringBuilder(string.Empty);
        string[] splitItems = null;
        string user = Page.User.Identity.Name;
        foreach (string item in sc)
        {


            if (item.Contains(","))
            {
                splitItems = item.Split(",".ToCharArray());
                sb.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}'); ", ds.InsertPlan("1", splitItems[0], splitItems[1], splitItems[2], splitItems[3], DateTime.Now, DateTime.Now, user, user, "Nil", 1));
            }

        }

        try
        {
            //Display a popup which indicates that the record was successfully inserted
            Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);

        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);

        }       
    }
}

任何帮助将不胜感激...

【问题讨论】:

  • 看起来问题出在从 splitItems araay 中获取项目。您能否在使用 splitItems[3] 时检查您的 splitItems 数组是否包含 4 个项目?
  • item 的值是多少?
  • @jadavparesh06 是的,我签入了,我可以看到里面有 4 个项目..
  • @GrantWinney 项目的值是日期、地点 1、地点 2、距离。
  • 吉鲁我删除了aspx代码以简化其他读者的问题。

标签: c# asp.net arraylist indexoutofboundsexception


【解决方案1】:

您的 sb.AppendFormat 格式字符串需要 5 项。

您说 ds.InsertPlan() 具有以下签名,并且 参数映射到 InsertPlan() 而不是 AppendFormat()。但是,InsertPlan() 返回一个 int,所以 AppendFormat() 只有一个参数,一个 int 值。

public virtual int InsertPlan(
       string Plan_ID,                                  <-   "1"
       string Place_1,                                  <- splitItems[0]
       string Place_2,                                  <- splitItems[1]
       string Distance,                                 <- splitItems[2]
       string Date,                                     <- splitItems[3]
       System.Nullable<System.DateTime> Created_Time,   <- DateTime.Now
       System.Nullable<System.DateTime> Updated_Time,   <- DateTime.Now
       string Created_by,                               <- user
       string Updated_By,                               <- user
       string Version_Status,                           <- "Nil"
       System.Nullable<int> p3                          <- 1
     )

您的代码:

sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ",

      ds.InsertPlan("1",            // <-- unless InsertPlan() returns an array, then this
                                    // is only 1 argument to the outer function
                    splitItems[0],
                    splitItems[1],
                    splitItems[2],
                    splitItems[3],
                    DateTime.Now, DateTime.Now, user, user, "Nil", 1
                   )
);

就像:

 sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ",      
                 1);                                // only {0} has a argument
                                                    // {1} ... {4} do not

【讨论】:

  • 我检查了一下,我看到 splititem 中有 4 个项目。
  • 是的,我看错了。它是关于 AppendFormat() 格式字符串,而不是数组。我修改了。
  • ds.InsertPlan 是一个数据集。我希望将这些值插入数据库中......任何替代方案。
  • 您的代码调用了 2 个函数,sb.AppendFormat 和 ds.InsertPlan。也许您应该先调用一个,而不是在参数列表中。
  • 查看我的编辑。您的参数都将转到 InsertPlan,它返回一个整数。为什么要将单个整数传递给 AppendFormat() ?你想附加什么?