Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I just started learning c# and I am getting an error saying Argument1: cannot co

ID: 3761912 • Letter: I

Question

I just started learning c# and I am getting an error saying Argument1: cannot convert from 'string' to 'int' how do i fix this?

I tried changing the values to integer from the beginnning and the values in the Dictionary<int, int> however, that doesn't seem to work.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

namespace BookCollection

{

//   class Database

//   {

        public class Database : Form

        {

            private List<Book> bookList;

            private Dictionary<int, int> index;

            public Database()

            {

                bookList = new List<Book>();

                index = new Dictionary<int, int>();

            }

           public int Add(Book b)

           // public string Add(Book b)

            {

                bookList.Add(b);

                int position = bookList.Count - 1;

                index.Add(b.Id, position); // this is the line with the error

                return position;

            }

            public void ShowDb()

            {

            string allBooks = "";

                foreach (Book b in bookList)

                {

                    allBooks += b.ToString() + " ";

                }

                MessageBox.Show(allBooks, "Books");

            }

            public Book FindById(int idValue)

            {

                int position;

                if (index.TryGetValue(idValue, out position))

                    return bookList[position];

                else

                    return null;

            }

        }

    }

I have another form that feeds this with this code

        private void btnAddBook_Click(object sender, EventArgs e)
        {
            //int bIsbn = int.Parse(txtISBN.Text);
            string bBookTitle = txtBookTitle.Text;
            string bAuthor = txtAuthor.Text;
            string bIsbn = txtISBN.Text;
            //int bIsbn = int32.parse(txtISBN.Text);
            Book b = new Book(bIsbn, bBookTitle, bAuthor);

            MessageBox.Show(b.ToString());
            db.Add(b);
            db.ShowDb();
        }

I have tried changing the values to integer from the get go, but it is not working.   

Explanation / Answer

Try to use Parse or TryParse function if book.Id is string

index.Add(int.Parse(b.Id), position); // this is the line with the error

OR

int id;

if(int.TryParse(b.Id,out id))

index.Add(id, position); // this is the line with the error