使用数据适配器填充数据 table 后无法使用数据 table.Find 方法

Cannot use data table.Find method after filling the data table using data adapter

我一直在为我的项目使用断开连接的模型。问题是我已经使用数据适配器 .Fill 命令来填充我的数据 table 并且它已经成功填充但是在填充数据 table 之后我无法使用 datatable.Find 方法来搜索基于其主键的数据。数据适配器不是应该在 fill 命令之后分配包括主键在内的所有内容吗? //DataRow r = dt.Rows.Find(BO.RoomNo); 这在调试时给出错误说不存在主键

因此,我不得不改用 foreach 循环

foreach (DataRow r in dt.Rows)
{
  if (BO.RoomNo == (int)r[1])
  {
    temp.RoomNo = (int)r[1];
    temp.Category = (string)r[2];
    temp.Price = (float)r[3];
    temp.Status = (string)r[4];
  }
}

您必须如下所述设置 DataTable 的主键 属性,

//ID is primary key
dt.PrimaryKey = new DataColumn[] { dt.Columns["ID"]};