locked
Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)

    السؤال

  •  

    private void txtLastName_Validating(object sender, CancelEventArgs e)

    {

     

    string tabSrc = @"Provider=VFPOLEDB;Data Source=C:\Users\dweiss\Documents\FoxPro Utilities\addressbook.dbc";

     

    string connSrc = "Provider=VFPOLEDB;Data Source=" + tabSrc;

     

    var cmdSrc = new OleDbCommand();

     

    var dbconnSrc = new OleDbConnection(connSrc);

    dbconnSrc.Open();

    cmdSrc.Connection = dbconnSrc;

    cmdSrc.CommandText =

    "select First_Name,Last_Name,Address1,Address2,City,State,Zip from address";

     

    var reader = cmdSrc.ExecuteReader(CommandBehavior.CloseConnection);

    reader.Read();

     

    txtFirstName.Text = reader[

    "First_Name"];

    reader.Close();

    }

    23/رمضان/1431 03:09 م

الإجابات

  • Try adding a ToString() to the reader object being accessed:

     

    txtFirstName.Text = reader["First_Name"].ToString(); 
    


    The reader is returning an object type, so it needs to be converted/cast/parsed to the expected data type. Alternately, if you know the column index, you can use the various GetXXX() methods provided by the SqlDataReader , where XXX corresponds to the desired type. For example, if "First_Name" is index 0, you could use:

     

    txtFirstName.Text = reader.GetString(0);
    
    

     

     


    Document my code? Why do you think it's called "code"?
    • تم وضع علامة كإجابة بواسطة Figo Fei 30/رمضان/1431 07:19 ص
    23/رمضان/1431 03:17 م
  • If you don't know the column index, you can still use GetXXX:

    txtFirstName.Text = reader.GetString(reader.GetOrdinal("First_Name"));

    • تم الاقتراح كإجابة بواسطة David Libido 23/رمضان/1431 07:30 م
    • تم وضع علامة كإجابة بواسطة Figo Fei 30/رمضان/1431 07:18 ص
    23/رمضان/1431 04:25 م

جميع الردود

  • Try adding a ToString() to the reader object being accessed:

     

    txtFirstName.Text = reader["First_Name"].ToString(); 
    


    The reader is returning an object type, so it needs to be converted/cast/parsed to the expected data type. Alternately, if you know the column index, you can use the various GetXXX() methods provided by the SqlDataReader , where XXX corresponds to the desired type. For example, if "First_Name" is index 0, you could use:

     

    txtFirstName.Text = reader.GetString(0);
    
    

     

     


    Document my code? Why do you think it's called "code"?
    • تم وضع علامة كإجابة بواسطة Figo Fei 30/رمضان/1431 07:19 ص
    23/رمضان/1431 03:17 م
  • If you don't know the column index, you can still use GetXXX:

    txtFirstName.Text = reader.GetString(reader.GetOrdinal("First_Name"));

    • تم الاقتراح كإجابة بواسطة David Libido 23/رمضان/1431 07:30 م
    • تم وضع علامة كإجابة بواسطة Figo Fei 30/رمضان/1431 07:18 ص
    23/رمضان/1431 04:25 م