Reputation: 540
I am quite new to c# and have stored positions of an object in a SQL Server database. I have written a query to select the object locations out of the database and now want to populate an array with these.
I have had trouble with 'you cannot convert an object to a point' etc errors and I cannot figure out how to populate an array with the point data type.
Could anyone help me with this?
Current code:
try
{
consecond.Open(); //Opens the connection
SqlDataReader dr = com_getposition.ExecuteReader();
int i = 0;
object[] arrayreturn = new object[10];
while (dr.Read())
{
arrayreturn[i] = dr["POSITION"];
i++;
}
p1.Location = (Point)arrayreturn[0];
dr.Close();
}
finally
{
consecond.Close(); //Closes the connection
}
Thanks
Upvotes: 0
Views: 503
Reputation: 46937
If POSITION
is of type nvarchar
you need to parse it (not cast it) into correct type.
var str = (string)dr["POSITION"];
var i = str.IndexOf(',', 3);
var x = int.Parse(str.Substring(3, i - 3));
var y = int.Parse(str.Substring(i + 3, str.Length - (i + 4)));
p1.Location = new Point(x, y);
Upvotes: 1
Reputation: 25053
Magnus is correct, but personally I prefer something like this:
Int32 n;
bool b = Int32.TryParse(arrayreturn[0].ToString(), out n);
if (b)
p1.Location = n;
If location
is a Point, then you can modify this:
Int32 x;
Int32 y;
bool b = Int32.TryParse(arrayreturn[0].ToString(), out x);
if (b) {
b = Int32.TryParse(arrayreturn[1].ToString(), out y);
if (b) {
p1.Location = new Point(x, y);
return;
}
}
// put error-handling code here
Upvotes: 0