2012-02-21 76 views
0

我對c#很新,並且已經存儲了SQL Server數據庫中對象的位置。我寫了一個查詢來選擇數據庫外的對象位置,現在想用這些查詢來填充一個數組。從SQL Server數據庫c創建一個點數組#

我遇到了'你不能將對象轉換爲點'等錯誤,我無法弄清楚如何用點數據類型填充數組。

任何人都可以幫助我嗎?

當前代碼:

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 
} 

感謝

+1

我們看一些代碼。 – jason 2012-02-21 21:11:58

+0

請提供您到目前爲止編寫的代碼 – northpole 2012-02-21 21:12:30

+1

sql查詢中的'POSITION'是什麼類型? – Magnus 2012-02-21 21:21:17

回答

1

如果POSITION的類型是nvarchar你需要分析它(不投吧)爲正確的類型。

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); 
+0

數據在數據庫中存儲(如視覺演播室顯示):{X = 390,Y = 197}「 – Mike91 2012-02-21 21:29:23

+0

感謝這麼多magnus,此代碼運行良好 – Mike91 2012-02-21 22:03:30

+0

沒問題,我看到這是你的第一個問題,別忘了接受答案 – Magnus 2012-02-21 22:06:27

0

馬格努斯是正確的,但我個人更喜歡這樣的事情:

Int32 n; 
bool b = Int32.TryParse(arrayreturn[0].ToString(), out n); 
if (b) 
    p1.Location = n; 

如果location是一個點,那麼你可以修改此:

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 
+0

感謝您的反饋egrunin,非常感謝! – Mike91 2012-02-21 22:03:39