LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發文檔 其他文檔  
 
網站管理員

WinForm 中如何給每一行 DataGridView 添加編輯刪除按鈕

admin
2025年5月18日 9:44 本文熱度 73

前言

WinForm 是 Microsoft .NET Framework 提供的一個圖形用戶界面(GUI)開發框架,憑借其簡單易用、功能豐富的特性,成為許多開發快速開發桌面應用程序的首選工具。在實際開發中,經常需要展示和操作表格數據,這時 DataGridView 控件就顯得尤為重要。

本文將介紹如何在 WinForm 中使用 DataGridView 控件,并通過添加"編輯"和"刪除"按鈕實現對每一行數據的交互式操作。

文章案例基于 Visual Studio 2022 編寫,適合初學者快速上手并掌握該控件的核心使用方法。

#WinForm開發技巧

DataGridView 控件

DataGridView 是 Windows Forms 中一個非常強大且靈活的表格控件,用于顯示和編輯結構化數據。它取代了舊版本中的 DataGrid 控件,提供了更豐富的功能和更好的用戶體驗。

主要特性包括:

  • 支持綁定多種類型的數據源,如 DataTable、List<T> 和數組;

  • 提供豐富的樣式設置選項,可自定義單元格外觀;

  • 支持排序、篩選和分組等高級功能;

  • 自定義列類型,如文本框、復選框、下拉框等;

  • 可動態添加或刪除行與列,支持單元格級別的編輯操作。

這些特性使得 DataGridView 成為 WinForm 開發中最常用的數據顯示控件之一。

運行效果

?
代碼實現

DataGridView 中添加編輯與刪除按鈕.

1、窗體代碼

public partialclassForm1 : Form
{
    private BindingSource bindingSource = new BindingSource();
    private List<Student> students = new List<Student>();
    privateint currentPage = 0;
    privateint pageSize = 10;
    public Form1()
    {
        InitializeComponent();
        CenterToParent();
        CenterToScreen();
        LoadData();
        // 設置分頁
        bindingSource.DataSource = GetPagedData(0, pageSize);
        dataGridView1.DataSource = bindingSource;
        // 添加編輯按鈕列
        DataGridViewButtonColumn editButtonColumn = new DataGridViewButtonColumn();
        editButtonColumn.Name = "Edit";
        editButtonColumn.HeaderText = "編輯";
        editButtonColumn.Text = "編輯";
        editButtonColumn.UseColumnTextForButtonValue = true;
        dataGridView1.Columns.Add(editButtonColumn);
        // 添加刪除按鈕列
        DataGridViewButtonColumn deleteButtonColumn = new DataGridViewButtonColumn();
        deleteButtonColumn.Name = "Delete";
        deleteButtonColumn.HeaderText = "刪除";
        deleteButtonColumn.Text = "刪除";
        deleteButtonColumn.UseColumnTextForButtonValue = true;
        dataGridView1.Columns.Add(deleteButtonColumn);
        Label_CurrentPageShow.Text = $"{currentPage+1}/{students.Count / 10}";
    }
    private void Form1_Load(object sender, EventArgs e)
    { 
    }
    private void LoadData()
    {
        // 假設我們有一些數據
        for (int i = 1; i <= 100; i++)
        {
            string id = (10000+i).ToString();
            students.Add(new Student { ID = id, Name = "Name" + i, Major = "Major" + i });
        }
    }
    private List<Student> GetPagedData(int pageIndex, int pageSize)
    {
        return students.Skip(pageIndex * pageSize).Take(pageSize).ToList();
    }
    private void btnPrevious_Click(object sender, EventArgs e)
    {
        if (currentPage > 0)
        {
            currentPage--;
            bindingSource.DataSource = GetPagedData(currentPage, pageSize);
            ShowPageNumber();
        }
    }
    private void btnNext_Click(object sender, EventArgs e)
    {
        if ((currentPage + 1) * pageSize < students.Count)
        {
            currentPage++;
            bindingSource.DataSource = GetPagedData(currentPage, pageSize);
            ShowPageNumber();
        }
    }
    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex >= 0)
        {
            // 獲取當前行的數據
            var student = (Student)bindingSource[e.RowIndex];
            if (e.ColumnIndex == dataGridView1.Columns["Edit"].Index)
            {
                // 編輯操作
                EditStudent(student);
            }
            elseif (e.ColumnIndex == dataGridView1.Columns["Delete"].Index)
            {
                // 刪除操作
                DeleteStudent(student);
            }
        }
    }
    private void EditStudent(Student student)
    {
        // 編輯邏輯,例如彈出一個對話框讓用戶編輯信息
        MessageBox.Show($"編輯: {student.Name}");
    }
    private void DeleteStudent(Student student)
    {
        if (MessageBox.Show($"刪除用戶:{student.Name}""確認刪除?", MessageBoxButtons.YesNo)== DialogResult.Yes)
        {
            // 刪除邏輯
            students.Remove(student);
            bindingSource.DataSource = GetPagedData(currentPage, pageSize);
            MessageBox.Show($"刪除成功: {student.Name}");
        }
    }
    InputBox inputBox = new InputBox();
    private void Btn_Add_Click(object sender, EventArgs e)
    {
        if (inputBox.OnValueComfirmChanged==null)
        {
            inputBox.OnValueComfirmChanged += ValueComfirmChangedCallback;
        }
        inputBox.Show();  
    }
    private void ValueComfirmChangedCallback(object sender, object receiver)
    {
        if(receiver!=null &&  receiver is Student)
        {
            Student student = (Student)receiver;
            student.ID = (10000 + students.Count).ToString();
            students.Add(student);
            ShowPageNumber();
        }
        inputBox.Hide();
    }
    public void ShowPageNumber()
    {
        int pageNum = 0;
        if (students.Count % 10>0)
        {
            pageNum = students.Count / 10+1;
        }
        else
        {
            pageNum = students.Count / 10;
        }
        Label_CurrentPageShow.Text = $"{currentPage + 1}/{pageNum}";
    }
}

2、數據代碼

public classStudent
{
    publicstring ID { getset; }
    publicstring Name { getset; }
    publicstring Major { getset; }
    public Student()
    {
    }
    public Student(string name ,string major)
    {
        Name = name;
        Major = major;
    }
}

3、輸入框代碼

public delegate void ValueComfirmChanged(object sender ,object receiver);
public ValueComfirmChanged OnValueComfirmChanged;
public InputBox()
{
    InitializeComponent();
    this.CenterToParent();
}
private void Btn_Comfirm_Click(object sender, EventArgs e)
{
    OnValueComfirmChanged?.Invoke(thisnew Student(Tbx_Name.Text,Tbx_Major.Text));
}
private void Btn_Cancel_Click(object sender, EventArgs e)
{
    Tbx_Name.Clear();
    Tbx_Major.Clear();
    this.Hide();
}

總結

DataGridView 是 WinForm 開發中不可或缺的數據展示控件,具備強大的功能和高度的可定制性。通過使用 DataGridViewButtonColumn,我們可以輕松地為每一行添加"編輯"和"刪除"按鈕,提升用戶操作的便捷性和直觀性。

本文介紹了 DataGridView 的基本特性和使用方式,并詳細演示了如何通過代碼實現按鈕列及其事件處理。對于剛接觸 WinForm 開發的新手來說,這是一個實用且易于理解的功能點,能夠幫助大家快速掌握數據表格操作的核心技巧。


閱讀原文:原文鏈接


該文章在 2025/5/19 10:02:24 編輯過
關鍵字查詢
相關文章
正在查詢...
點晴ERP是一款針對中小制造業的專業生產管理軟件系統,系統成熟度和易用性得到了國內大量中小企業的青睞。
點晴PMS碼頭管理系統主要針對港口碼頭集裝箱與散貨日常運作、調度、堆場、車隊、財務費用、相關報表等業務管理,結合碼頭的業務特點,圍繞調度、堆場作業而開發的。集技術的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業的高效ERP管理信息系統。
點晴WMS倉儲管理系統提供了貨物產品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質期管理,貨位管理,庫位管理,生產管理,WMS管理系統,標簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務都免費,不限功能、不限時間、不限用戶的免費OA協同辦公管理系統。
Copyright 2010-2025 ClickSun All Rights Reserved

黄频国产免费高清视频,久久不卡精品中文字幕一区,激情五月天AV电影在线观看,欧美国产韩国日本一区二区
亚洲香蕉网久久综合影视 | 亚洲Av电影在线观看不卡 | 在线不卡的午夜福利 | 亚洲欧美日韩高清专区一 | 亚洲视频精品在线人 | 亚洲一级a爱视频在线 |