C# 数据表中缺少主键
当我运行以下代码从C# 数据表中缺少主键,c#,C#,当我运行以下代码从DataTable获取值时,我得到一个错误 System.Data.dll中发生“System.Data.MissingPrimaryKeyException”类型的异常,但未在用户代码中处理 我不知道原因和如何修复它。我得到的错误是 if (csvData.Rows.Find(args.BluetoothAddress.ToString()) != null) 我的完整代码: string csv_file_path = @"C: \Users\xxx\Desktop\xx
DataTable
获取值时,我得到一个错误
System.Data.dll中发生“System.Data.MissingPrimaryKeyException”类型的异常,但未在用户代码中处理
我不知道原因和如何修复它。我得到的错误是
if (csvData.Rows.Find(args.BluetoothAddress.ToString()) != null)
我的完整代码:
string csv_file_path = @"C: \Users\xxx\Desktop\xxxx.csv";
DataTable csvData;
.....
DataColumn[] primaryKeys;
primaryKeys = csvData.PrimaryKey;
.....
private void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
if (args.RawSignalStrengthInDBm > -100)
{
if (csvData.Rows.Find(args.BluetoothAddress.ToString()) != null)
// got the error
{
DataRow infoRow = csvData.Rows.Find(args.BluetoothAddress.ToString());
if (infoRow[1] != null)
{
// Display Location information
this.Dispatcher.Invoke((Action)(() =>
{ textBox.Text = ("Location: " + infoRow[2].ToString() + ", Time: " + DateTime.Now.ToString("h:mm:ss tt")).ToString(); }));
}
else
{
// record other information
........
}
}
}
}
当表没有主键时,将引发
MissingPrimaryKeyException
要在数据行集合上执行查找
,需要在数据表上定义
,请尝试定义主键,如下例所示
DataColumn column1=... ; // Table column
csvData.PrimaryKey = new DataColumn[] {column1};
当表没有主键时,将引发MissingPrimaryKeyException
要在数据行集合上执行查找
,需要在数据表上定义
,请尝试定义主键,如下例所示
DataColumn column1=... ; // Table column
csvData.PrimaryKey = new DataColumn[] {column1};
您忘记设置应被视为数据表中主键的列或列组。以下是您如何做到这一点:
DataTable csvData = new DataTable();
DataColumn idCol = new DataColumn("Id",typeof(int));
//column should be already added into the column list of datatable before setting it as primary key
csvData.Columns.Add(idCol);
//set the primary key. Here you can add multiple columns as it is a array property. This fixes your error
csvData.PrimaryKey = new[] { idCol };
DataColumn[] primaryKeys;
primaryKeys = csvData.PrimaryKey;
//if you do not set the primary key the below count was earlier coming out to be zero.
var count = primaryKeys.Length;
您忘记设置应被视为数据表中主键的列或列组。以下是您如何做到这一点:
DataTable csvData = new DataTable();
DataColumn idCol = new DataColumn("Id",typeof(int));
//column should be already added into the column list of datatable before setting it as primary key
csvData.Columns.Add(idCol);
//set the primary key. Here you can add multiple columns as it is a array property. This fixes your error
csvData.PrimaryKey = new[] { idCol };
DataColumn[] primaryKeys;
primaryKeys = csvData.PrimaryKey;
//if you do not set the primary key the below count was earlier coming out to be zero.
var count = primaryKeys.Length;
您能指出引发异常的行吗?if(csvData.Rows.Find(args.BluetoothAddress.ToString())!=null)。此行出错。您能指出引发异常的行吗?if(csvData.Rows.Find(args.BluetoothAddress.ToString())!=null)。这条线出错了。