0

我有一个绑定到 DataTable 的 DataGridView。我添加了一个 DataGridViewButtonColumn 作为该行的删除按钮。

由于它绑定到 DataTable,我希望能够通过单击删除按钮获取行的对象,以便我可以从 DataTable 中删除它,然后刷新 DataGrid。

这就是我的按钮的设置方式:

  var colDelete = new DataGridViewButtonColumn();
  colDelete.Name = "DeleteButton";
  colDelete.HeaderText = "Delete";
  colDelete.Text = "Delete";
  colDelete.UseColumnTextForButtonValue = true;
  colDelete.DataPropertyName = "EthnicityDetailID";
  colDelete.DisplayIndex = 10;
  dataGridEthnicityData.Columns.Add(colDelete);

这就是我计划处理按钮单击事件的方式:

private void dataGridEthnicityData_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        try
        {
            var senderGrid = (DataGridView)sender;

            if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
                e.ColumnIndex == senderGrid.Columns["DeleteButton"].Index)
            {
                

                //ethnicityDataTable.Rows.RemoveAt(e.RowIndex);
                dataGridEthnicityData.Refresh();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error deleting ethnicity data: " + ex.Message + " " + ex.StackTrace);
        }

    }

如何将 EthnicityDetailID 分配为按钮的值,以及如何检索单击按钮作为对象的行,以便我可以检索值并在数据表中相应地删除?

谢谢你。

4

1 回答 1

1

显然,您已将 DataTable 绑定到 DataGridView 的 DataSource。如果您将数据与数据的显示方式分开,您将拥有类似于以下内容的代码:

BindingList<Ethnicity> DisplayedEthnicities
{
    get => (BindingList<Ethnicity>) this.dataGridView1.DataSource,
    set => this.dataGridView1.DataSource = value;
}

Ethnicity GetEthnicity(DataGridViewRow row)
{
    return (Ethnicity)row.DataboundItem;
}

Ethnicity CurrentEthnicity => this.dataGridView1.CurrentCell?.OwnindRow as Ethnicity;

IEnumerable<Ethnicity> SelectedEthnicities => this.dataGridView1.SelectedRows
    .Select(row => this.GetEthnicity(row));

您还需要在 Datatable 和 Ethnicity 之间进行转换:

void IEnumerable<Ethnicities> ToEthnicities(DataTable dataTable)
{
      // TODO: convert the rows of the datatable into Ethnicities
}

你比我更了解你的数据表中的种族。

在此之后,填充 DataGridView 将很容易:

DataTable CreateDataTable()
{
    // TODO: fill the datatable with data from database? CSV file? Json?
}

void FillDataGridView()
{
    var dataTable = this.CreateDataTable();
    var ethnicities = this.ToEthnicities(dataTable);
    this.DisplayedEthnicities = new BindingList<Enthnicity>(ethnicities.ToList());
}

我希望能够通过单击删除按钮来获取行的对象

像这样完成之后,获取数据绑定项将很容易:

void OnCellContent_Clicked(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewRow row = this.DataGridView1.Rows[e.RowIndex];
    Ethnicity ethnicity = this.GetEthnicity(row);
    ProcessEthnicity(ethnicity);
}
于 2021-01-11T10:00:08.213 回答