迴圈可變化的集合 數組 datatable 等 || c# winfrom DataGridView 動態UI下載功能

来源:https://www.cnblogs.com/BFMC/p/18020935
-Advertisement-
Play Games

Gif演示 分解步驟 1,使用組件DataGridView 2,使用DataSource來控製表格展示的數據來源(註意:來源需要是DataTable類型) 3,需要用到非同步線程。如果是不控制數據源的話,需要使用UI安全線程;(使用Control.Invoke或Control.BeginInvoke方 ...


Gif演示

 

分解步驟

1,使用組件DataGridView

2,使用DataSource來控製表格展示的數據來源(註意:來源需要是DataTable類型)

3,需要用到非同步線程。如果是不控制數據源的話,需要使用UI安全線程;(使用Control.Invoke或Control.BeginInvoke方法)

4,DataGridView的列如果設置圖片,儘量代碼設置

5,DataTable類型也是可以使用LINQ的,參考:AsEnumerable

完整代碼

using Newtonsoft.Json;
using Sunny.UI.Win32;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinApp.i18n;
using WinApp.Until;
using WinApp.ViewModel;
using static System.Net.Mime.MediaTypeNames;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Security.Cryptography;

namespace WinApp.View
{
    public partial class DownloadList : UserControl
    {
        /// <summary>
        /// 開啟任務的開關(作用:禁止重覆啟動任務)
        /// </summary>
        private static bool _taskSwitch = true;
        /// <summary>
        /// 任務中的小開關(作用:如果被外部干涉,則進行退出執行任務內容)
        /// </summary>
        private static bool _taskCondition = true;

        public DataTable _table;
        List<DownloadListDto> _mainList;

        public UILabel _lbNotData;

        public DownloadList()
        {
            InitializeComponent();
            var mainTitle = string.Empty;
            mainTitle = Language.GetLang("downloadTitle1");
            mainTitle += "\r" + Language.GetLang("downloadTitle2");
            this.uiPanel1.Text = mainTitle;

            uiDataGridView1.ColumnHeadersVisible = false;
            uiDataGridView1.RowTemplate.Height = 65;
            uiDataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None;

            _lbNotData = new UILabel();
            _lbNotData.Text = "No more data available";
            _lbNotData.Cursor = Cursors.Hand;
            _lbNotData.TextAlign = ContentAlignment.MiddleCenter;
            _lbNotData.Location = new Point(450, 50);
            _lbNotData.Width = 200;
            _lbNotData.Visible = false;
            this.uiPanel2.Controls.Add(_lbNotData);
        }

        private void DownloadList_Load(object sender, EventArgs e)
        {
            QueryData();
        }

        public void SetCondition(bool setValue)
        {
            _taskCondition = setValue;
        }
        public async Task DownloadAllAsync()
        {
            if (_taskSwitch)
            {
                if (_table.Rows.Count <= 0)
                {
                    UIMessageDialog.ShowMessageDialog("No more data available", UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false);
                    return;
                }


                //已經執行,請勿重覆執行;
                _taskSwitch = false;


                foreach (DataRow row in _table.Rows)
                {
                    row["Status"] = "2";//設置為下載中的狀態
                    uiDataGridView1.Refresh();
                }

                while (_table.Rows.Count > 0 && _taskCondition)
                {//如果列表有數據就一直迴圈進行下載刪除
                    var firstRow = _table.Rows[0];
                    if (firstRow == null)
                    {//第一個元素等於NULL
                        return;
                    }

                    for (int j = 0; j <= 100; j++)//模擬進度條
                    {
                        if (_taskCondition)
                        {//如果沒有暫停
                            await Task.Delay(10); // wait for 100 milliseconds
                            firstRow["DownloadProgress"] = j.ToString();

                        }
                        else
                        {//暫停
                            firstRow["Status"] = "1";
                        }
                    }

                    if (_taskCondition)
                    {
                        // 獲取當前行的數據行                    
                        var _Id = (int)firstRow["Id"];
                        // 使用Linq查詢匹配的行
                        var rowsToDelete = _table.AsEnumerable().FirstOrDefault(row => row.Field<int>("Id") == _Id);
                        _table.Rows.Remove(rowsToDelete);
                    }
                }

                //foreach (DataRow row in _table.Rows)
                //{
                //    row["Status"] = "2";

                //    for (int j = 0; j <= 100; j++)
                //    {
                //        if (_taskCondition)
                //        {
                //            await Task.Delay(10); // wait for 100 milliseconds
                //            row["DownloadProgress"] = j.ToString();
                //        }
                //        else
                //        {
                //            row["Status"] = "1";
                //        }
                //    }
                //    // 獲取當前行的數據行                    
                //    var _Id = (int)row["Id"];
                //    // 使用Linq查詢匹配的行
                //    var rowsToDelete = _table.AsEnumerable().FirstOrDefault(row => row.Field<int>("Id") == _Id);
                //    _table.Rows.Remove(rowsToDelete);
                //}


                //foreach (var item in _mainList)
                //{
                //    item.Status = 2;
                //    uiDataGridView1.Refresh();

                //    for (int i = 0; i < 100; i++)
                //    {
                //        if (_taskCondition)
                //        {
                //            await Task.Delay(100); // wait for 100 milliseconds
                //            item.DownloadProgress = i.ToString();
                //            uiDataGridView1.Refresh();
                //        }
                //        else
                //        {
                //            item.Status = 1;
                //            return;
                //        }
                //    }
                //}

                //執行完畢,則可以重新執行
                _taskSwitch = true;
            }
            else
            {
                //因為此次沒有執行,下次允許執行;
                _taskSwitch = true;
                return;
            }
        }

        public void PauseAll()
        {
            SetCondition(false);

            //獲取所有已經開始的數據

            var pauseList = _table.AsEnumerable().Where(row => row.Field<int>("Status") == 2);
            foreach (DataRow item in pauseList)
            {
                item["Status"] = "1";
                uiDataGridView1.Refresh();
            }

        }

        public void DeleteAll()
        {            
            SetCondition(false);
         
            // 清除所有行
            _table.Clear();
            uiDataGridView1.Refresh();
            this.uiDataGridView1.Refresh();
        }

        public void QueryData()
        {

            LoadingHelper.ShowLoadingScreen();

            _mainList = new List<DownloadListDto>();
            _mainList.Add(new DownloadListDto()
            {
                Id = 1,
                Title = "A1" + Environment.NewLine + "B1",
                Status = 1,
                DownloadProgress = "0"
            });
            _mainList.Add(new DownloadListDto()
            {
                Id = 2,
                Title = "A2" + Environment.NewLine + "B2",
                Status = 1,
                DownloadProgress = "0"
            });
            _mainList.Add(new DownloadListDto()
            {
                Id = 3,
                Title = "A3" + Environment.NewLine + "B3",
                Status = 1,
                DownloadProgress = "0"
            });
            _mainList.Add(new DownloadListDto()
            {
                Id = 4,
                Title = "A4" + Environment.NewLine + "B4",
                Status = 1,
                DownloadProgress = "0"
            });
            _mainList.Add(new DownloadListDto()
            {
                Id = 5,
                Title = "A5" + Environment.NewLine + "B5",
                Status = 1,
                DownloadProgress = "0"
            });


            _table = _mainList.ToDataTable();
            this.uiDataGridView1.DataSource = _table;

            LoadingHelper.CloseForm();
            uiDataGridView1.ClearSelection();
        }

        private void uiDataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            DataGridViewRow row = uiDataGridView1.Rows[e.RowIndex];

            if (uiDataGridView1.Columns[e.ColumnIndex].Name == "clTitle")
            {
                if (row.Cells["clStatus"].Value is int)
                {
                    var intStatus = (int)row.Cells["clStatus"].Value;
                    if (intStatus == 1)
                    {
                        row.Cells["clOpDown"].Value = FileHelper.loadImageFromLocalPath(@"FileFolder/Icon/downLoad.png");
                        row.Cells["clOpDelete"].Value = FileHelper.loadImageFromLocalPath(@"FileFolder/Icon/delete1.png");
                    }
                    else if (intStatus == 2)
                    {
                        row.Cells["clOpDown"].Value = FileHelper.loadImageFromLocalPath(@"FileFolder/Icon/pause.png");
                        row.Cells["clOpDelete"].Value = FileHelper.loadImageFromLocalPath(@"FileFolder/Icon/delete1.png");
                        //row.Cells["clOpDelete"].Value = null;
                    }
                    else
                    {
                        // 創建一個1x1像素的透明圖像
                        Bitmap transparentImage = new Bitmap(1, 1);
                        transparentImage.SetPixel(0, 0, Color.Transparent);
                        row.Cells["clOpDown"].Value = transparentImage;
                        row.Cells["clOpDelete"].Value = transparentImage;
                    }
                }

            }
        }

        private void uiDataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //uiDataGridView1.ClearSelection();
        }

        private async void uiDataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (uiDataGridView1.Columns[e.ColumnIndex] is DataGridViewImageColumn && e.RowIndex >= 0)
            {
                // 獲取當前行的數據行
                var currentRow = uiDataGridView1.Rows[e.RowIndex];
                var _Id = (int)currentRow.Cells["clId"].Value;
                if (uiDataGridView1.Columns[e.ColumnIndex].Name == "clOpDown")
                {

                    //var currentData = _mainList.Find(x => x.Id == _Id);
                    var currentData = _table.AsEnumerable().FirstOrDefault(x => x.Field<int>("Id") == _Id);
                    if (currentData != null)
                    {
                        if (currentData["Status"].ToString() == "1")
                        {//1代表 未下載

                            currentData["Status"] = "2";//修改圖標
                            uiDataGridView1.Refresh();

                        }
                        else
                        {//2代表 正在下載

                            _taskCondition = false;//終止執行任務
                            currentData["Status"] = "1";//修改圖標
                            uiDataGridView1.Refresh();

                        }
                        //currentData.Status = 1;
                        //_taskCondition = false;
                        //uiDataGridView1.Refresh();
                    }
                }

                if (uiDataGridView1.Columns[e.ColumnIndex].Name == "clOpDelete")
                {

                    // 使用Linq查詢匹配的行
                    var rowsToDelete = _table.AsEnumerable().FirstOrDefault(row => row.Field<int>("Id") == _Id);
                    _table.Rows.Remove(rowsToDelete);
                }
            }
        }
        public void DeleteMainData(int Id)
        {
            var currentData = _mainList.Find(x => x.Id == Id);
            if (currentData != null)
            {
                _mainList.Remove(currentData);
                uiDataGridView1.DataSource = _mainList;
                uiDataGridView1.Refresh();
            }
        }

        private void uiDataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            uiDataGridView1.Visible = true;
            _lbNotData.Visible = false;
            DataGridView dataGridView = (DataGridView)sender;
            if (dataGridView.Rows.Count == 0)
            {
                uiDataGridView1.Dock = DockStyle.None;
                uiDataGridView1.Visible = false;

                _lbNotData.Visible = true;
            }
        }

        private void uiDataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            // 取消預設的錯誤處理行為
            e.ThrowException = false;

            // 獲取出錯的單元格
            DataGridViewCell errorCell = uiDataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];

            // 獲取出錯的數據
            object errorValue = uiDataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

            // 自定義錯誤處理邏輯
            MessageBox.Show("數據錯誤:" + e.Exception.Message);

            // 可以將出錯的單元格的值重置為預設值
            errorCell.Value = errorCell.DefaultNewRowValue;
        }
    }
}

 

結語

上面完整代碼是.cs的代碼。大家拷貝本地使用的時候需要在UI界面進行拖拉組件。本例子用的是winform SunnyUI 的框架 。框架文檔在這裡:文檔預覽 - Gitee.com

從前慢,車馬慢。 一生只愛一個人。
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 今天我們主要講解的是Spring依賴註入。在本文中,我們主要圍繞bean填充屬性的欄位和setter方法展開討論。要記住的是,在進行屬性註入時,我們首先需要找到註入點併進行緩存,然後才會真正進行屬性註入。需要註意的是,靜態欄位或方法是不會進行依賴註入的。最後,我們簡單地介紹了一下關鍵源碼,以及對@R... ...
  • 通過`FromStr`及`Display`的重定義,我們可以支持更強大的自定義的序列化操作,系統綁定埠既認埠號也認綁定IP,所以我們可以對同個埠進行多次綁定。 ...
  • python打包和反編譯 從py到exe 打包 安裝Pyinstaller pip install pyinstaller //太慢可切源 pip install -i https://pypi.douban.com/simple/ pyinstaller #豆瓣源 pip install -i h ...
  • API介面是一種讓不同系統之間實現數據交互的工具,它可以實現不同系統之間的數據共用和數據傳遞。全國今日油價API介面是一項非常有用的介面,它可以提供最新的全國各省汽油和柴油價格信息。本文將為大家介紹全國今日油價API介面的使用方法,並提供相應代碼說明。 介面名稱:全國今日油價API介面介面地址:ht ...
  • 當我們在編寫代碼時,經常會遇到需要管理資源的情況,比如打開和關閉文件,如果遇到了一些異常情況,我們需要關閉資源,不然會導致資源泄露,雖然我們可以通過手動的方式來關閉,但如果有多個異常情況需要考慮的話,萬一不小心漏了一處,就芭比Q了。所以,如果有一種更加優雅的方式來處理資源泄露的問題,那必定是非常ni ...
  • 拓展閱讀 sensitive-word-admin v1.3.0 發佈 如何支持分散式部署? sensitive-word-admin 敏感詞控台 v1.2.0 版本開源 sensitive-word 基於 DFA 演算法實現的高性能敏感詞工具介紹 更多技術交流 業務背景 如果我們的敏感詞部署之後,不 ...
  • Java 方法 簡介 方法是一塊僅在調用時運行的代碼。您可以將數據(稱為參數)傳遞到方法中。方法用於執行特定的操作,它們也被稱為函數。 使用方法的原因 重用代碼:定義一次代碼,多次使用。 提高代碼的結構化和可讀性。 將代碼分解成更小的模塊,易於維護和理解。 創建方法 方法必須在類內聲明。它的定義包括 ...
  • 前言我個人對三維渲染領域的開發有著濃厚的興趣,儘管並未在相關行業工作過,我的瞭解還很片面。去年,在與群友聊天時,他們推薦了一本《Unity Shader入門精要》,說適合像我這樣想自學的新人,於是我打開了通往新世界的大門。這本書涵蓋了很多基礎的渲染知識,如光照、陰影、各種風格的渲染等等。對於有興趣的 ...
一周排行
    -Advertisement-
    Play Games
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...
  • 目錄前言PostgreSql安裝測試額外Nuget安裝Person.cs模擬運行Navicate連postgresql解決方案Garnet為什麼要選擇Garnet而不是RedisRedis不再開源Windows版的Redis是由微軟維護的Windows Redis版本老舊,後續可能不再更新Garne ...
  • C#TMS系統代碼-聯表報表學習 領導被裁了之後很快就有人上任了,幾乎是無縫銜接,很難讓我不想到這早就決定好了。我的職責沒有任何變化。感受下來這個系統封裝程度很高,我只要會調用方法就行。這個系統交付之後不會有太多問題,更多應該是做小需求,有大的開發任務應該也是第二期的事,嗯?怎麼感覺我變成運維了?而 ...
  • 我在隨筆《EAV模型(實體-屬性-值)的設計和低代碼的處理方案(1)》中介紹了一些基本的EAV模型設計知識和基於Winform場景下低代碼(或者說無代碼)的一些實現思路,在本篇隨筆中,我們來分析一下這種針對通用業務,且只需定義就能構建業務模塊存儲和界面的解決方案,其中的數據查詢處理的操作。 ...
  • 對某個遠程伺服器啟用和設置NTP服務(Windows系統) 打開註冊表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer 將 Enabled 的值設置為 1,這將啟用NTP伺服器功 ...
  • title: Django信號與擴展:深入理解與實踐 date: 2024/5/15 22:40:52 updated: 2024/5/15 22:40:52 categories: 後端開發 tags: Django 信號 松耦合 觀察者 擴展 安全 性能 第一部分:Django信號基礎 Djan ...
  • 使用xadmin2遇到的問題&解決 環境配置: 使用的模塊版本: 關聯的包 Django 3.2.15 mysqlclient 2.2.4 xadmin 2.0.1 django-crispy-forms >= 1.6.0 django-import-export >= 0.5.1 django-r ...
  • 今天我打算整點兒不一樣的內容,通過之前學習的TransformerMap和LazyMap鏈,想搞點不一樣的,所以我關註了另外一條鏈DefaultedMap鏈,主要調用鏈為: 調用鏈詳細描述: ObjectInputStream.readObject() DefaultedMap.readObject ...
  • 後端應用級開發者該如何擁抱 AI GC?就是在這樣的一個大的浪潮下,我們的傳統的應用級開發者。我們該如何選擇職業或者是如何去快速轉型,跟上這樣的一個行業的一個浪潮? 0 AI金字塔模型 越往上它的整個難度就是職業機會也好,或者說是整個的這個運作也好,它的難度會越大,然後越往下機會就會越多,所以這是一 ...
  • @Autowired是Spring框架提供的註解,@Resource是Java EE 5規範提供的註解。 @Autowired預設按照類型自動裝配,而@Resource預設按照名稱自動裝配。 @Autowired支持@Qualifier註解來指定裝配哪一個具有相同類型的bean,而@Resourc... ...