【问题标题】:Datagridview is set to public but still "does not exist" on other formsDatagridview 设置为公开,但在其他表单上仍然“不存在”
【发布时间】:2021-11-18 11:19:58
【问题描述】:

我正在尝试从表单 1 datagridview 中的选定行中获取单元格的值。我想将此值存储在一个变量中,以便我可以使用该变量使用适当的 ID 更新我的数据库中的特定条目。

我已经在属性中将 datagridview 设置为 public,但由于某种原因,它仍然无法识别我其他表单上的 datagrid。我的代码在表格 2 上如下所示:

                   var selectedAppointmentId = appointmentDgv.CurrentRow.Cells[0].Value;

                   Appointment appointment = new Appointment();
                   appointment.AppointmentID = int.Parse((string)selectedAppointmentId);

此代码位于编辑按钮中,以便我可以对数据库进行更改。我不断收到错误消息:“当前上下文中不存在名称‘appointmentDgv’”。我对 C# 比较陌生。

【问题讨论】:

标签: c# datagridview


【解决方案1】:

考虑将 DataGridView 的数据加载到分配给 BindingSource 的 DataTable(或 T 列表)中,BindingSource 设置为 DataGridView 的 DataSource。

订阅 BindingSource 的PositionChanged 事件。

使用 DataGridView 在表单中设置属性,例如说主键。由于 setter 是私有的,因此值只能在子窗体中更改,而不能在调用窗体中更改,因此它受到保护。

public int CurrentIdentifier { get; private set; }

在 BindingSource 的 PositionChanged 事件中获取您需要的值,在本例中是来自 DataRow 的主键。这里的 BindingSource 名称是 _customerBindingSource

if (_customerBindingSource.Current == null)
{
    CurrentIdentifier = -1;
}
CurrentIdentifier = (_customerBindingSource.Current as DataRowView).Row.Field<int>("Id");

在需要值的表单中,为上面的表单创建一个私有属性,然后获取值,在这种情况下为 Id。

if (_childForm.CurrentIdentifier > -1)
{
    var appointment = new Appointment { AppointmentID = _childForm.CurrentIdentifier };
}
else
{
    // no current row
}

通过使用 BindingSource,您无需触摸 DataGridView 中的单元格,数据是强类型的。此外,BindingSource 有很多好处,您应该花时间去探索。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多