forritarik
forritarik

Reputation: 35

C++Builder - cannot cast from 'AnsiString' to 'TObject'

I have a problem with converting a string variable to TObject.

I have a query that returns two columns to me. In the first column I have varchar values that I translate into strings, and in the second column I have int values.

I want to fill a ComboBox in this way with these values:

cbx1-> AddItem (DataSet1->DataSet->Fields->Field[0]->AsString, (TObject *) (int) DataSet1->DataSet->Fields->Field[1];

As I refer to the second value which is int type, I receive some bushes, e.g., xD, etc.

By trying to convert this value to string, eg:

String temp = IntToStr (DataSet1->DataSet->Fields->Field[1]);
cbx1-> AddItem (DataSet1->DataSet->Fields->Field[0]->AsString, (TObject *) temp;

I receive an error message:

cannot cast from 'AnsiString' to 'TObject'

I do not know what further I can do to convert this value.

Upvotes: 1

Views: 490

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596236

You cannot cast an AnsiString value to a TObject* pointer. You can only cast an integer value, or a pointer value, to a TObject* pointer. AnsiString is neither of those.

You are not retrieving the int value from the 2nd field correctly anyway. Field[1] is a pointer to an actual TField object in the Fields collection. That pointer is what you are trying to store in your ComboBox, NOT the int value that the TField represents.

You need to call Fields[1]->AsInteger to get the int value of the 2nd field, similar to how you use Fields[0]->AsString to get the string value of the 1st field:

cbx1->AddItem(
    DataSet1->DataSet->Fields->Field[0]->AsString,
    (TObject*) DataSet1->DataSet->Fields->Field[1]->AsInteger
    // in C++, using reinterpret_cast is preferred over C-style casting:
    // reinterpret_cast<TObject*>(DataSet1->DataSet->Fields->Field[1]->AsInteger)
);

This is no different than the code in your previous question:

cbx1->AddItem("one",(TObject*)1);

You are now just placing the literals "one" and 1 with runtime variables of equivalent types.

Upvotes: 1

Related Questions