如何访问DataGridView数据

时间:2016-01-19 18:43:59

标签: c# .net datagridview datagridviewcolumn

一般的标题,但我不确定如何总结这种情况:

我有一个包含多行和6列的DGV。在带有这个DGV的表格上,我有几个按钮来添加,编辑,删除和保存DGV的状态(图1)。当用户单击“编辑”按钮时,将打开一个带有TextBoxes的新窗口,该窗口应填充所选行中的数据(图2)。

我的问题是,传递行数据的最佳方法是什么(通过DataGridViewRow或DataGridViewCellCollection),一旦传递给Edit类,我该如何访问行的数据。一旦我能收到这个,剩下的应该是我的蛋糕,但我不确定如何访问单元格的数据。

代码张贴在图片下方。

图1:Main form with DGV & buttons

图2 :(不确定为什么它如此巨大,抱歉!)

Edit window for cell data

代码链接:

以下是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;
    }
}

1 个答案:

答案 0 :(得分:2)

首先,使用SelectedRows属性而不是数据格式视图的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
    }
}