我遇到了我绝对毫无头绪的最奇怪的错误。我将在此处发布说明以及一些代码,希望你们中的一个可以为我指明正确的方向。

我的应用程序(Winforms)允许用户将项目添加到datagridview(绑定(bind)到列表),并且每次添加项目时,列表都会序列化为xml文件。最初启动应用程序时,程序将检查xml文件,如果找到该文件,则将先前添加的项目添加到dgv。

Ive还添加了一个DataGridViewButtonColumn来从dgv(列表)中删除项目。这是一些代码。

主类:

 static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new formFoldingClient());
        }

表单的构造函数调用此方法来初始设置dgv
private void InitialDataGridViewSetup()
        {
            dgvClients.DataSource = null;

            //adding delete button column
            DataGridViewButtonColumn btnDelete = new DataGridViewButtonColumn();
            btnDelete.Name = "btnDelete";
            btnDelete.Text = "Delete";
            btnDelete.HeaderText = "Delete";
            btnDelete.UseColumnTextForButtonValue = true;
            btnDelete.DefaultCellStyle.BackColor = Color.DarkBlue;
            btnDelete.DefaultCellStyle.ForeColor = Color.White;
            dgvClients.Columns.Add(btnDelete);

            RefreshDataGridView();
        }

每次添加或删除项目时,通过调用以下方法刷新dgv:
 private void RefreshDataGridView()
            {
                dgvClients.DataSource = null;

                if (clientList.Count != 0)
                {
                    dgvClients.DataSource = clientList;
                    dgvClients.Show();
                    dgvClients.ClearSelection();


                }
            }

Method that gets triggered when Delete button on a row in the dgv is pressed, followed by the method the performs the delete

 private void dgvClients_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0) //delete button has been clicked
            {
                DeleteClient(dgvClients.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].FormattedValue.ToString());
            }
        }

        private void DeleteClient(string clientToDelete)
        {
            dgvGrid.DataSource = null;
            int removeAt = new int();

            for (int i=0; i<clientList.Count; i++)
            {
                if (clientList[i]._ClientName == clientToDelete)
                {
                    removeAt = i;
                    break;
                }
            }

            clientList.RemoveAt(removeAt);
            LogToFile("Removed client: " + clientToDelete);
            LogToBox("Removed client: " + clientToDelete);
            RefreshDataGridView();
            SaveConfigAsXml();
            LogToFile("Changes after deletion persisted to clients.xml.");

        }

我相信这是所有必须使用的代码。如果您需要更多,请告诉我。

问题简介
当应用程序首次找到它的XML并将其加载到列表中时,一切都会按预期执行。我可以添加更多项,一次删除所有项,等等。

但是,如果我开始时没有初始xml,则添加项目不是问题。但是,当我删除dgv中最后剩余的项时,在Main()的最后一行得到了以下异常
Index out of range Exception: {"Index -1 does not have a value."}

堆栈跟踪
at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)
   at System.Windows.Forms.CurrencyManager.get_Current()
   at System.Windows.Forms.DataGridView.DataGridViewDataConnection.OnRowEnter(DataGridViewCellEventArgs e)
   at System.Windows.Forms.DataGridView.OnRowEnter(DataGridViewCell& dataGridViewCell, Int32 columnIndex, Int32 rowIndex, Boolean canCreateNewRow, Boolean validationFailureOccurred)
   at System.Windows.Forms.DataGridView.SetCurrentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick)
   at System.Windows.Forms.DataGridView.OnCellMouseDown(HitTestInfo hti, Boolean isShiftDown, Boolean isControlDown)
   at System.Windows.Forms.DataGridView.OnCellMouseDown(DataGridViewCellMouseEventArgs e)
   at System.Windows.Forms.DataGridView.OnMouseDown(MouseEventArgs e)
   at System.Windows.Forms.Control.WmMouseDown(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.DataGridView.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at FoldingMonitorLocalClient.Program.Main() in C:\Users\xbonez\Documents\Visual Studio 2010\Projects\FoldingClient\FoldingClient\Program.cs:line 17
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

更多信息
因此,我刚刚意识到,如果dgv中有n个项目,则仅删除第一个项目也会导致相同的异常。删除项目2至n没问题。


读取xml并将其添加到列表中的代码
 private void ReadFromConfigFile()
        {
            LogToFile("Beginning to read from clients.xml.");

            XmlSerializer deserializer = new XmlSerializer(typeof(List<Client>));

            try
            {
                List<Client> tempClientList = new List<Client>();
                using (Stream reader = new FileStream("clients.xml", FileMode.Open))
                {
                    tempClientList = ((List<Client>)deserializer.Deserialize(reader));
                }

                foreach (Client client in tempClientList)
                {
                    clientList.Add(client);
                }
            }
            catch (FileNotFoundException ex)
            {
                //config file does not exist
                this.LogToBox("No saved settings found.");
                this.LogToFile("No existing clients.xml present.", ex);
            }
            catch (Exception ex)
            {
                LogToBox("Unable to load saved settings. Please see log for more details.");
                LogToFile("Failed to read clients.xml.", ex);
            }
            finally
            {
                LogToFile("Finished reading clients.xml.");
            }
        }

单击添加按钮时的代码
private void btnAdd_Click(object sender, EventArgs e)
        {
            this.tbxClientName.BackColor = Color.White;
            this.tbxLogLoc.BackColor = Color.White;

            bool exists = false;

            foreach (Client client in clientList)
            {
                if (client._ClientName == this.tbxClientName.Text)
                    exists = true;
            }

            if (String.IsNullOrEmpty(tbxClientName.Text))
            {
                this.tbxClientName.BackColor = Color.Yellow;
                LogToBox("Enter Client Name");
                LogToFile("user attempted to add client without specifying client name.");
            }
            else if (String.IsNullOrEmpty(tbxLogLoc.Text))
            {
                this.tbxLogLoc.BackColor = Color.Yellow;
                LogToBox("Select WorkLog location.");
                LogToFile("User attempted to add client without specifying worklog location.");
            }
            else if (exists)
            {
                //client name entered by user already exists
                LogToBox("Client name " + this.tbxClientName.Text + " already exists. Enter another Client name.");
                LogToFile("Duplicate client name entered.");
                this.tbxClientName.BackColor = Color.Yellow;
            }
            else
            {
                //everything is valid. Add new client to list
                clientList.Add(new Client(tbxClientName.Text, tbxLogLoc.Text));
                LogToBox("Added new client: " + tbxClientName.Text + ".");
                LogToFile("Added new client: " + tbxClientName.Text + ".");

                this.tbxClientName.Text = String.Empty;
                this.tbxLogLoc.Text = String.Empty;

                RefreshDataGridView();
                SaveConfigAsXml();
            }
        }

最佳答案

这似乎是.NET中的某种内部绑定(bind)错误。
每当使用绑定(bind)到列表的DataGridView时,我都会遇到完全相同的异常。
我确实花了很多时间试图找到解决方案,今天终于设法摆脱了这些异常(exception)情况-将ICurrencyManagerProvider接口(interface)添加到我的所有列表中。
该接口(interface)仅具有“CurrencyManager”只读属性和“GetRelatedCurrencyManager”方法。
我只是在两者中都返回Nothing,仅此而已,不再是CurrencyManager中“索引-1没有值”的东西。

关于c# - 索引1没有值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4965963/

10-12 06:42