QuickLearner
QuickLearner

Reputation: 89

Miss primary key in data table

When I run the following code to get the value from DataTable, I get an error

An exception of type 'System.Data.MissingPrimaryKeyException' occurred in System.Data.dll but was not handled in user code

I do not know the reason and how to fix it. The line I got the error is

if (csvData.Rows.Find(args.BluetoothAddress.ToString()) != null)

My full code:

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
                ........
            }
        }
    }
}

Upvotes: 0

Views: 1351

Answers (2)

RBT
RBT

Reputation: 25877

You have forgot to set the column or group of columns which should be considered as Primary key in the data table. Here is how you can do it:

    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;

Upvotes: 1

Hari Prasad
Hari Prasad

Reputation: 16956

MissingPrimaryKeyException is thrown when the table does not have a primary key.

In order to do Find on a DataRowCollection you need PrimaryKey defined on a DataTable, try defining primary key as shown in below example.

DataColumn column1=... ; // Table column
csvData.PrimaryKey = new DataColumn[] {column1};

Upvotes: 1

Related Questions