Lakshan Enosh
Lakshan Enosh

Reputation: 219

C# get values separated by commas (,) and en dash (-) in the multi-lined Textbox and insert them into multiple rows and columns in database

I am implementing a software to save books. So I want to add many authors and theirs roles to a book. So i'm Typing author name and his role separated with a (-) en hash and I add many authors to one book by using (,) in the textbox.
Look at this image for more info.
Image :- Adding a new book to the database
My Book Table

RecordID| BookID  | Book Name        | ISBN     |
---------------------------------------------------
001     |125      |Journey of my life|0123456789|

My Author Table

RecordID| AuthorID| Author Name
---------------------------------
001     |005      |B.A. Lakshan Enosh  
002     |006      |John williams  
003     |007      |graham winter  
004     |008      |Dilshan nim  

Book_Author Table

RecordID| BookID  | AuthorID| ROLE|  
---------------------------------  
001     |125      |005      |Author|  
002     |125      |006      |Author|  
003     |125      |007      |Editor|  
004     |125      |008      |Editor| 

i need to insert values to my many to many relationship table in the database like above.

My question - How can i separate data in the textbox and insert them to the my many to many table.

(Please Refer the picture I have attached before giving me bad comments) Thank you

Upvotes: 0

Views: 957

Answers (2)

user8654026
user8654026

Reputation:

According to your picture, the format is like:

name1 - role1, name2 - role2, name3 - role3

Please try below to split into each pair of name and role.

string strAuthorRole = txtAuthorRole.Text;
string[] lstAuthorRole = strAuthorRole.Split(',');
string[] lstAuthor = new string[lstAuthorRole.Length];
string[] lstRole = new string[lstAuthorRole.Length];
string strMsg = "";

for (int i = 0; i < lstAuthorRole.Length; i++)
{
    string[] pair = lstAuthorRole[i].Split('-');
    lstAuthor[i] = pair[0].Trim();
    lstRole[i] = pair[1].Trim();
    // sample output
    strMsg += lstAuthor[i] + " (" + lstRole[i] + ")\n";
}

MessageBox.Show(strMsg);

By using lstAuthor and lstRole, you can then insert each pair (having same index in the arrays) into your table. Hope this helps.

Upvotes: 1

Prasad Telkikar
Prasad Telkikar

Reputation: 16049

if I understood it correctly then your text format is like

name of author - role1, role2, role3

This can be seperate out in two steps

step 1. Separate author and roles.

Step 2. Separate roles into multiple separate roles

Here is the code. Try it out

        string[] authorRoles = yourString.Split('-');
        string[] roles = authorRoles[1].Split(',');

Upvotes: 1

Related Questions