2013-01-04 68 views
1

請幫助即時通訊新的C#剛讀它有錯誤的腳本並沒有產生下一個數字 錯誤顯示「使用指定的局部變量最大的」 這條線上發現最大數量及產生下一個數字

"maxCommand.Parameters.Add("@acn", SqlDbType.VarChar).Value = max.ToString();" 

完整編碼

private void contact_edit_Click(object sender, EventArgs e) 
     { 
      int max; 
      SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\fuda\\Fuda.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"); 
      con.Open(); 
      SqlCommand maxCommand = new SqlCommand(); 
      maxCommand = con.CreateCommand(); 
      maxCommand.CommandText = ("SELECT max(acn) from contacts"); 
      maxCommand.Parameters.Add("@acn", SqlDbType.VarChar).Value = max.ToString(); 
      maxCommand.ExecuteNonQuery(); 
      max = max ++; 
      acn.Text = max.ToString(); 

     } 

怎麼能安排???

example acn = 2253 \\ in table "contact" coulmn acn (A/c number) 
if acn = 2253 \\collected max number from acn 
acn + 1 \\ add 1 to acn 
acn = 2254 \\this should be generate 

回答

0

max的初始值未知。指定一個值可以解決問題。

int max = 0; 

要找到max和下一個值,你可以嘗試

maxCommand.CommandText = ("SELECT acn FROM contacts ORDER BY acn DESC"); 
    SqlDataReader reader = maxCommand.ExecuteReader(); 
    reader.Read(); 
    max = Convert.ToInt32(reader[0]); // the max value 
    max++;// the next value 
    acn.Text = max.ToString(); 
+0

它只是顯示0它我以前不從SQL表的列名讀ACN –

+0

maxCommand.Parameters.Add爲佔位符分配值在SQL語句中。要從SQL檢索值,您應該使用[SqlCommand.ExecuteReader](http://msdn.microsoft.com/en-us/library/9kcbe65k.aspx) – neo

+0

等方法否我的意思是我想要生成下一個數字示例如果你的代碼的結果是2253,那麼它應該是2254,這是新的數字......! –