2

I would like to insert an array of strings into a table in PostgreSQL using Npgsql in C#. I have written the code below but am getting an InvalidCastexception.

eventcommand.Parameters.AddWithValue("@participants", NpgsqlDbType.Array).Value = participant.Text;

where participant is an textbox and eventcommand is an NpgsqlCommand.

1 Answer 1

3

You're calling AddWithValue, but not providing the value - you're providing the type. Additionally, you're not providing an array - you're just providing a single string. I suspect you just want:

command.Parameters.Add("@participants", NpgsqlDbType.Array | NpgsqlDbType.Text).Value
    = new[] { participant.Text };

Or you may want to split participant.Text into an array of strings first, or something similar.

(I've adjusted the type as per comments.)

Sign up to request clarification or add additional context in comments.

2 Comments

Note also that NpgsqlDbType.Array needs to be bitwise ORed with the element type, so NpgsqlDbType.Array | NpgsqlDbType.Text for array of strings
@Shay: Thanks, fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.