簡體   English   中英

如何在C#Winforms中不使用數據庫的情況下在列表上使用DatagridView

[英]How to use DatagridView on a List without using Database in C# Winforms

在我的項目中,我想從文件中讀取數據並將DataGridView更新為一個簡單的List。 我想要這樣做,以便可以在運行時更新列表,然后在保存后希望將列表的最終內容更新為文件。

在google搜索中看到的大多數解決方案中,我都提供了有關如何使用DatagridView和數據庫連接來更新DatagridView的示例。 進行插入,更新和刪除操作。 我的答案有很多建議,包括添加基於INotifyProperty和IBindingList的實現,這可能是一個過大的殺傷力。

我只打算發布涉及使用Datagridview更新列表的解決方案。 此處使用的代碼段是一個大型項目的一部分,該項目將數據從Datagridview更新到列表,然后再返回,這是一個很大的挑戰,因為最初需要使用數據庫來實現,而依賴關系則需要刪除。

發布此問題時,我已經解決了我的問題。 為了解決這個問題,我從先前的各種問題中獲取了一些零碎的建議。 我不是在評論中尋找建議。 如果有人想向我展示解決此問題的更好方法,請發布包含工作代碼的答案。

因此,閱讀后,您將獲得一系列MyData對象。 您要在DataGridView中顯示所有MyData對象(或子部分)。

操作員可以更改顯示的值,添加一些新行或刪除行。 有些列可能是只讀的,無法更改

按下確定按鈕后,您想要從DataGridView讀取所有MyData對象並將它們保存在文件中。

您的大部分工作都可以使用表單設計器來完成。

  • 在設計器中打開表單類
  • 在此表單上拖動一個DataGridView
  • 在此表單上拖動BindingSource
  • 右鍵單擊BindingSource並選擇屬性
  • 在右側的箭頭中,單擊“數據源”中的屬性窗口。
  • 如果MyData在此處不可見,請選擇“添加項目數據源”。
  • 在新窗口中選擇對象
  • 選擇添加的數據源作為BindingSource的DataSource
  • 在DataGridView的屬性中,將您的bindingSource分配給DataSource

突然之間:您的DataGridView具有MyData的公共屬性的列。 神奇的是,這些列具有正確的類型。 他們能夠顯示值。 只讀屬性具有只讀列,讀寫屬性是可編輯的。

要顯示數據:

void FillDataGridView(IEnumerable<MyData> dataToDisplay)
{
    this.bindingSource1.DataSource = new BindingList<MyData>(dataToDisplay.ToList();
}

編輯后讀取所有數據

IEnumerable<MyData> ReadDataGridView()
{
    return this.bindingSource1.List.Cast<MyData>();
}

這使操作員可以添加和刪除行以及編輯值。 如果您不希望操作員執行此操作,請調整DataGridView屬性。如果列的顯示值不符合您的喜好,請編輯列屬性(不同的標題文本,不同的顯示格式,不同的背景顏色等)

這是一個示例,其中我使用DatagridView在列表(類對象PersonState列表)上執行插入更新和刪除。

DatagridView的數據源需要包含一個DataTable,為了彌合這一差距,我使用了一個名為ConvertToDatatable()的函數。

首先,我從Anup Kumar Sharma在另一個鏈接上建議的項目開始。

在此處輸入圖片說明

使用以下代碼:

using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;

namespace InsertUpdateDelete {
    public partial class Form1 : Form {
        public class PersonState {
            public string Name { get; set; }
            public string State { get; set; }
        }
        public List<PersonState> listOfPersonState;
        public Form1() {
            InitializeComponent();
            listOfPersonState = new List<PersonState>();
        }
        //Display Data in DataGridView  
        private void DisplayData() {
            DataTable dt = new DataTable();
            dt = ConvertToDatatable();
            dataGridView1.DataSource = dt;
        }
        //Clear Data  
        private void ClearData() {
            txt_Name.Text = "";
            txt_State.Text = "";
        }
        public DataTable ConvertToDatatable() {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("State");
            foreach (var item in listOfPersonState) {
                var row = dt.NewRow();
                row["Name"] = item.Name;
                row["State"] = item.State;
                dt.Rows.Add(row);
            }
            return dt;
        }
        private void AddToList(string text1, string text2) {
            listOfPersonState.Add(new PersonState { Name = text1, State = text2 });
        }
        private void UpdateToList(string text1, string text2) {
            int index = dataGridView1.SelectedRows[0].Index;
            listOfPersonState[index] = new PersonState { Name = text1, State = text2 };
        }
        private void DeleteToList() {
            int index = dataGridView1.SelectedRows[0].Index;
            listOfPersonState.RemoveAt(index);
        }
        private void btn_Insert_Click(object sender, EventArgs e) {
            if (txt_Name.Text != "" && txt_State.Text != "") {
                AddToList(txt_Name.Text, txt_State.Text);
                //MessageBox.Show("Record Inserted Successfully");
                DisplayData();
                ClearData();
            } else {
                MessageBox.Show("Please Provide Details!");
            }
        }
        private void btn_Update_Click(object sender, EventArgs e) {
            if (txt_Name.Text != "" && txt_State.Text != "") {
                if (dataGridView1.SelectedRows != null && dataGridView1.SelectedRows.Count > 0) {
                    UpdateToList(txt_Name.Text, txt_State.Text);
                    //MessageBox.Show("Record Updated Successfully");
                    DisplayData();
                    ClearData();
                }    
            } else {
                MessageBox.Show("Please Select Record to Update");
            }
        }
        private void btn_Delete_Click(object sender, EventArgs e) {
            if (dataGridView1.SelectedRows != null && dataGridView1.SelectedRows.Count > 0) {
                DeleteToList();
                //MessageBox.Show("Record Deleted Successfully!");
                DisplayData();
                ClearData();
            } else {
                MessageBox.Show("Please Select Record to Delete");
            }
        }

        private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
            FillInputControls(e.RowIndex);
        }
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
            FillInputControls(e.RowIndex);
        }
        private void FillInputControls(int Index) {
            if (Index > -1) {
                txt_Name.Text = dataGridView1.Rows[Index].Cells[0].Value.ToString();
                txt_State.Text = dataGridView1.Rows[Index].Cells[1].Value.ToString();
            }
        }
    }
}

學到:

  1. 觀察到我在課堂上使用了屬性。

而不是使用:

public class PersonState {
    public string Name;
    public string State;
}

我用過:

public class PersonState {
    public string Name { get; set; }
    public string State { get; set; }
}

由於某些原因,前者在嘗試評估值時不起作用。

  1. 我已經將對象列表設為類變量,以便所有函數都可以直接訪問該列表,而不必將其作為參數傳遞。

    public List<PersonState> listOfPersonState;

  2. 我替換了插入,更新和刪除到數據庫,插入更新和刪除到列表的邏輯。

     private void AddToList(string text1, string text2) { listOfPersonState.Add(new PersonState { Name = text1, State = text2 }); } private void UpdateToList(string text1, string text2) { int index = dataGridView1.SelectedRows[0].Index; listOfPersonState[index] = new PersonState { Name = text1, State = text2 }; } private void DeleteToList() { int index = dataGridView1.SelectedRows[0].Index; listOfPersonState.RemoveAt(index); } 

注意:我是直接從列表中分配網格,因此我的網格和列表始終具有相同的索引,因為我正在使用顯示功能來確保在“插入”,“更新”和“刪除”按鈕操作上做到這一點。

private void DisplayData() {
    DataTable dt = new DataTable();
    dt = ConvertToDatatable();
    dataGridView1.DataSource = dt;
}
public DataTable ConvertToDatatable() {
    DataTable dt = new DataTable();
    dt.Columns.Add("Name");
    dt.Columns.Add("State");
    foreach (var item in listOfPersonState) {
        var row = dt.NewRow();
        row["Name"] = item.Name;
        row["State"] = item.State;
        dt.Rows.Add(row);
    }
    return dt;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM