How to insert two or more different values under one column name based on parent PK?

Simflex 326 Reputation points
2025-06-02T16:04:54.6866667+00:00

Greetings experts,

We are designing internal ballot system that will be used to elect members into various positions based on election types.

Developer technologies | VB
0 comments No comments
{count} vote

3 answers

Sort by: Most helpful
  1. KOZ6.0 6,735 Reputation points
    2025-06-07T08:03:33.87+00:00

    Are you talking about a DataTable? Although a DataTable column cannot have multiple values, a Primary Key can be created from multiple columns.

    Sub Main()
        Dim dt As New DataTable()
        dt.Columns.Add("KEY1")
        dt.Columns.Add("KEY2")
        dt.Columns.Add("Item")
        dt.PrimaryKey = New DataColumn() {dt.Columns("KEY1"), dt.Columns("KEY2")}
        dt.Rows.Add("1", "1", "A")
        dt.Rows.Add("1", "2", "B")
        dt.Rows.Add("1", "1", "C") ' System.Data.ConstraintException
    End Sub
    
    0 comments No comments

  2. Surya Amrutha Vaishnavi Lanka (INFOSYS LIMITED) 245 Reputation points Microsoft External Staff
    2025-07-03T11:44:10.0166667+00:00

    Reason is multiple entries under the same primary key combination, which is causing a System.Data.ConstraintException due to the primary key constraint you defined. In a DataTable, each primary key combination must be unique, which is why you're seeing that error.

    Different approach

    Use a Separate Table: Instead of trying to insert multiple values into the same DataTable, you could create a separate DataTable to manage the multiple entries. The primary table can reference this table using foreign keys.

    Use Composite Key: If every unique combination is required but the actual "item" values vary, consider creating a composite key in your DataTable that includes additional columns to differentiate items.


  3. Surya Amrutha Vaishnavi Lanka (INFOSYS LIMITED) 245 Reputation points Microsoft External Staff
    2025-07-08T04:41:11.88+00:00

    Hope you're doing well , we're following up on the ticket. Please let us know issue persist are resolved.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.