簡體   English   中英

如何訪問DataGridView數據

[英]How to access DataGridView data

有點籠統的標題,但是我不確定如何總結這種情況:

我有幾行六列的DGV。 在具有此DGV的表單上,我有幾個按鈕可以用於添加,編輯,刪除和保存DGV的狀態(圖1)。 當用戶單擊Edit按鈕時,將打開一個帶有TextBoxes的新窗口,其中應填充來自選定行的數據(圖2)。

我的問題是,(通過DataGridViewRow或DataGridViewCellCollection)傳遞行數據的最佳方法是什么,一旦將其傳遞給Edit類,我該如何訪問行數據。 一旦收到此消息,剩下的對我來說應該是小菜一碟,但是我不確定如何訪問單元的數據。

代碼在圖片下方發布。

圖1: 帶DGV和按鈕的主窗體

圖2 :(不確定為什么這么大,對不起!)

單元格數據的編輯窗口

代碼片段:

這是DGV的“編輯有軌電車”按鈕的代碼:

private void buttonEditRailCar_Click(object sender, EventArgs e)
    {
        var singleCarSelected = this.dataGridViewSimulatedTrainEditor.CurrentRow;

        EditRailCar editNewRailCar = new EditRailCar(singleCarSelected);

        //To StackOverFlow: Feel free to ignore anything below this comment!

        var result = editNewRailCar.ShowDialog();

        if (result == DialogResult.OK)
        {                
            this.NewSimulatedTrain.Add(addNewRailCar.NewSimulatedTrain);
            this.WereChangesMade = true;
            this.buttonSaveXML.Enabled = true;
        }
    }

這是用文本框彈出的Edit Rail Car FORM的代碼,我將在行中填充數據-我添加了一些偽代碼,以便您可以看到我要實現的目標:

public partial class EditRailCar : Form
{
    public EditRailCar(DataGridViewRow t)
    {
        InitializeComponent();

        //Here, when the form opens, the local textboxes should be populated with data
            //from the DGV's cells
        this.textBoxName.Text = t.RailCarName;
        this.textBoxRailCarType.Text = t.RailCarType;
        this.textBoxVelocity.Text = t.Velocity;
        this.textBoxVelocityDistance.Text = t.VelocityDistance;
        this.textBoxIsDamaged.Text = t.IsDamage;
        this.textBoxIsForeignObject.Text = t.IsForeignObject;
    }

    private void buttonSaveEdits_Click(object sender, EventArgs e)
    {
        //This will save the changes to the current row in the DGV
        //StackOverFlow may ignore this :)
    }

    private void buttonCancelNewCar_Click(object sender, EventArgs e)
    {
        DialogResult = DialogResult.Cancel;
    }
}

首先,使用SelectedRows屬性代替datagridview的CurrentRow

if (this.dataGridViewSimulatedTrainEditor.SelectedRows.Count > 0)
{
    var singleCarSelected = this.dataGridViewSimulatedTrainEditor.SelectedRows[0];
}

同樣,您過去的方式是完全錯誤的。 寧可創建RetailCar類型,填充它並像這樣傳遞它

public class RetailCar
{
  public string Name {get; set;}
  public string Type {get; set;}

  // rest propetties
}

DataGridViewRow rw = this.dataGridViewSimulatedTrainEditor.SelectedRows[0];
RetailCar rc = new RetailCar
{
  Name = rw.Cells["RetailCar Name"].Value.ToString();
  Type = rw.Cells["RetailCar Type"].Value.ToString();

  // fill rest properties
};

傳遞它

EditRailCar editNewRailCar = new EditRailCar(rc);

相應地更改表單構造函數

public partial class EditRailCar : Form
{
    public EditRailCar(RetailCar retailCar)
    { 
        // do whatever needed
    }
}

暫無
暫無

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

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