Hi everybody

I wanted to retrieve data from sql server and save them in arrayList
I use the following format

sql="select bookid,bookname from BookTable";
Sqlcommand cmd=new (sql,conn)
// I define reader here
while(reader.Read())
{
list.Add(new book(reader[reder.GetName(0)],reader[reader.GetName(1)]));
}

in book class I build a constructor

public book(int id,String name)
{
this.id=id;
this.name=name;
}

but it always says specified cast invalid then I put

Convert.ToInt32(reader[reader.GetName(0)])
but it does not work please help me because I really feel headache from thinking of that
How can I convert from SQL server data format to C# format ????
:sad:

Because, you are retreiving onyl two different values from db, you can use Directory with key (id) and value (book name).

Dictionary<int, string> list = new Dictionary<int, string>();
            while (reader.Read())
            {
                int idBook = (int)reader[0];
                string nameBook = (string)reader[1];
                list.Add(idBook, nameBook);                
            }

If you still want to use Array list you can use the code bellow, but you need to seperate id ,and book name, (and id has to be converted to string):

ArrayList list = new ArrayList();
            while (reader.Read())
            {
                int idBook = (int)reader[0];
                string nameBook = (string)reader[1];
                list.Add(idBook.ToString() + "-" + nameBook);                
            }

Edited 5 Years Ago by Mitja Bonca: n/a

This article has been dead for over six months. Start a new discussion instead.