winform刪除dataGridView列報異常:System.IndexOutOfRangeException:“索引 7 沒有值

来源:https://www.cnblogs.com/taxue/archive/2019/11/30/11962657.html
-Advertisement-
Play Games

winform界面如下: 1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using S ...


winform界面如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 using System.Windows.Forms;
10 
11 namespace form1
12 {
13     public partial class Form1 : Form
14     {
15         List<Student> data = GetStudents();
16         public Form1()
17         {
18             InitializeComponent();
19 
20             this.dataGridView1.DataSource = data;
21         }
22 
23 
24         public static List<Student> GetStudents()
25         {
26 
27             return new List<Student>()
28             {
29                 new Student{ ID =1,Name="小a",Age=18},
30                 new Student{ ID =2,Name="小b",Age=18},
31                 new Student{ ID =3,Name="小c",Age=18},
32                 new Student{ ID =4,Name="小d",Age=18},
33                 new Student{ ID =5,Name="小e",Age=18},
34                 new Student{ ID =6,Name="小f",Age=18},
35                 new Student{ ID =7,Name="小g",Age=18},
36                 new Student{ ID =8,Name="小k",Age=18}
37 
38             };
39 
40         }
41         private void tsmDelete_Click(object sender, EventArgs e)
42         {
43 
44             List<Student> students = new List<Student>();
45             foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
46             {
47                 var student = row.DataBoundItem as Student;
48                 if (student != null)
49                 {
50                      data.Remove(student);
51                    // students.Add(student);
52                 }
53             }
54            
55             for (int i = 0; i < students.Count(); i++)
56             {
57                 data.Remove(students[i]);
58             }
59             this.dataGridView1.DataSource = null;
60             this.dataGridView1.DataSource = data;
61         }
62     }
63 }
View Code

問題說明:右鍵刪除行的時候異常,System.IndexOutOfRangeException:“索引 7 沒有值。

 

 

刪除的代碼如下:

 private void tsmDelete_Click(object sender, EventArgs e)
        {
          
            foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
            {
                var student = row.DataBoundItem as Student;
                if (student != null)
                {
                     data.Remove(student);    
                }
            }
            this.dataGridView1.DataSource = null;
            this.dataGridView1.DataSource = data;
        }

修改後的代碼:

        private void tsmDelete_Click(object sender, EventArgs e)
        {

            List<Student> students = new List<Student>();
            foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
            {
                var student = row.DataBoundItem as Student;
                if (student != null)
                {                   
                students.Add(student);
                }
            }

            for (int i = 0; i < students.Count(); i++)
            {
                data.Remove(students[i]);
            }
            this.dataGridView1.DataSource = null;
            this.dataGridView1.DataSource = data;
        }

異常的原因分析:

 this.dataGridView1.SelectedRows獲取選中的行,假設刪除的是第7行和第8行。

遍歷去取刪除這兩行,類型DataGridViewRow 直接引用數據源中的值。第7行刪除以後總行數就變成了7行 row.DataBoundItem去根據索引取第8行的值就超出了索引。



 

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • https://blog.csdn.net/wang839305939/article/details/78713124/ ...
  • 1.當前日期格式化: time.strftime('%Y-%m-%d',time.localtime(time.time())) 例子:輸出當前日期: import timeprint(time.strftime('%Y-%m-%d',time.localtime(time.time()))) 2. ...
  • WinForm界面使用IrisSkin,可以說做到了一鍵美化,當然美化的效果仁者見仁智者見智,可以挑選自己喜歡的。 1、IrisSkin下載地址:http://www.pc6.com/softview/SoftView_70918.html#download 2、將下載的文件放到Debug下麵。 3 ...
  • 在同一個地方摔倒兩次之後,決定記錄下來這個東西。 問題 在同一個地方摔倒兩次之後,決定記錄下來這個東西。 問題 1>uafxcwd.lib(afxmem.obj) : error LNK2005: "void * __cdecl operator new(unsigned int)" (??2@YA ...
  • 第二篇隨筆 9102年11月底,工科男曹**要算一個方程f(x)=0的根,其中f(x)表達式為: 因為實數範圍內f(x)=0的根太多,所以本文只研究-2<x<2的情況.這個式子長的太醜了,曹**看著覺得不爽,導之,得一f'(x) 這個式子更醜,但是,我們有牛頓迭代法,可以構造迭代序列{xn}滿足: ...
  • [TOC] Aso.Net Core 的配置系統Configuration ​ 1.以前的配置文件格式為XML ​ 2.新版的配置文件格式支持 { json ,xml, ini, memory, command, env..... } 01.Json文件的弱類型方式讀取 1. Json文件 【Mic ...
  • 一、在C#中,使用命名空間(Namespace)可以幫助控制自定義類型的作用範圍,同時對大量的類型進行組織;使用namespace關鍵字聲明命名空間,命名空間可以嵌套使用: namespace MyNameSpace { namespace MyNestedNameSpace { class MyC ...
  • 一個簡單的api模板項目,基於.netcore 3.0,其中包含swagger文檔,jwt許可權驗證,模型驗證,ioc,appEvent,分塊上傳等等現成的功能,幫你快速開始api的構建 ...
一周排行
    -Advertisement-
    Play Games
  • C#TMS系統代碼-基礎頁面BaseCity學習 本人純新手,剛進公司跟領導報道,我說我是java全棧,他問我會不會C#,我說大學學過,他說這個TMS系統就給你來管了。外包已經把代碼給我了,這幾天先把增刪改查的代碼背一下,說不定後面就要趕鴨子上架了 Service頁面 //using => impo ...
  • 委托與事件 委托 委托的定義 委托是C#中的一種類型,用於存儲對方法的引用。它允許將方法作為參數傳遞給其他方法,實現回調、事件處理和動態調用等功能。通俗來講,就是委托包含方法的記憶體地址,方法匹配與委托相同的簽名,因此通過使用正確的參數類型來調用方法。 委托的特性 引用方法:委托允許存儲對方法的引用, ...
  • 前言 這幾天閑來沒事看看ABP vNext的文檔和源碼,關於關於依賴註入(屬性註入)這塊兒產生了興趣。 我們都知道。Volo.ABP 依賴註入容器使用了第三方組件Autofac實現的。有三種註入方式,構造函數註入和方法註入和屬性註入。 ABP的屬性註入原則參考如下: 這時候我就開始疑惑了,因為我知道 ...
  • C#TMS系統代碼-業務頁面ShippingNotice學習 學一個業務頁面,ok,領導開完會就被裁掉了,很突然啊,他收拾東西的時候我還以為他要旅游提前請假了,還在尋思為什麼回家連自己買的幾箱飲料都要叫跑腿帶走,怕被偷嗎?還好我在他開會之前拿了兩瓶芬達 感覺感覺前面的BaseCity差不太多,這邊的 ...
  • 概述:在C#中,通過`Expression`類、`AndAlso`和`OrElse`方法可組合兩個`Expression<Func<T, bool>>`,實現多條件動態查詢。通過創建表達式樹,可輕鬆構建複雜的查詢條件。 在C#中,可以使用AndAlso和OrElse方法組合兩個Expression< ...
  • 閑來無聊在我的Biwen.QuickApi中實現一下極簡的事件匯流排,其實代碼還是蠻簡單的,對於初學者可能有些幫助 就貼出來,有什麼不足的地方也歡迎板磚交流~ 首先定義一個事件約定的空介面 public interface IEvent{} 然後定義事件訂閱者介面 public interface I ...
  • 1. 案例 成某三甲醫預約系統, 該項目在2024年初進行上線測試,在正常運行了兩天後,業務系統報錯:The connection pool has been exhausted, either raise MaxPoolSize (currently 800) or Timeout (curren ...
  • 背景 我們有些工具在 Web 版中已經有了很好的實踐,而在 WPF 中重新開發也是一種費時費力的操作,那麼直接集成則是最省事省力的方法了。 思路解釋 為什麼要使用 WPF?莫問為什麼,老 C# 開發的堅持,另外因為 Windows 上已經裝了 Webview2/edge 整體打包比 electron ...
  • EDP是一套集組織架構,許可權框架【功能許可權,操作許可權,數據訪問許可權,WebApi許可權】,自動化日誌,動態Interface,WebApi管理等基礎功能於一體的,基於.net的企業應用開發框架。通過友好的編碼方式實現數據行、列許可權的管控。 ...
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...