-1

I am trying to auto-complete and i get this error and i don't know how to fix it

Here is my code :

void AutoCompleteText(){
        Search_Box.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
        Search_Box.AutoCompleteSource = AutoCompleteSource.CustomSource;
        AutoCompleteStringCollection coll = new AutoCompleteStringCollection();

        SqlCeCommand cmd = new SqlCeCommand("select * from Contact_List   ;", con);
        SqlCeDataReader reader;
        try
        {
            con.Open();
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                string sName = reader.GetString("Name");
                coll.Add(sName);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        Search_Box.AutoCompleteCustomSource = coll;
    }

I get this error from

string sName = reader.GetString("Name");

and I also get : cannot convert from 'String' to 'int'

Need help please

L.Chan
  • 17
  • 2
  • 5
    The DataReader `GetString` function wants a column index number, not a column name. You can just use `reader["Name"].ToString()` instead. – LarsTech Jun 08 '16 at 16:56
  • 5
    It's telling you what the problem is. You need to pass an int, not a string. I suggest reading the documentation. – Heretic Monkey Jun 08 '16 at 16:59

1 Answers1

-2

SqlReader supports the "Get" by using a column name. (SqlReader is not what you have).

IDataReader and DbDataReader "Get" methods need an ORDINAL Number. like 0, 1, 2.

Here is a variation to show what I'm talking about:

   SqlCeCommand cmd = new SqlCeCommand("select MyInt32Column, MyVarCharColumn, MyBitColumn from MyTable;", con);
    SqlCeDataReader reader;
    try
    {
        con.Open();
        reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            int myInt32Value = reader.GetInt32(0);
            string myStringValue = reader.GetString(1);
            bool myBooleanValue = reader.GetBoolean(2);
        }

Bonus: You could also have an issue with the datatype. If so, you can do this:

Use the "GetValue(N)" method.

something like this

object o = reader.GetValue(0);
string mytype = o.GetType().ToString();

this is DEBUGGING code..it will show you the value and the datatype.

then put back the correct .GetString or GetInt32, etc, etc.

PS

This is the danger of using "select *". you should be in the column names. I'll repeat that, you should put in the column names, so you can see which columns you are expecting.

granadaCoder
  • 26,328
  • 10
  • 113
  • 146