2014-02-06 45 views
0

這是我使用的代碼,它會在第3個命令中彈出一個Exception .CommandText賦值,但它與我在第2個命令中使用的方法相同.CommandText賦值,輸入字符串在SqlCommand中的格式不正確

SqlCommand command = conn.CreateCommand(); 
    conn.Open(); 
    //1st 
    command.CommandText = query; 
    SqlDataReader reader = command.ExecuteReader(); 
    ArrayList alMainGrid = new ArrayList(); 

    while (reader.Read()) 
    { 

    SupportTable table = new SupportTable(); 
    table.LaySheetNo = reader.GetValue(0).ToString(); 
    table.PlnLayStartTime = reader.GetDateTime(1).ToString(); 
    table.PlnLayEndTime = reader.GetValue(2).ToString(); 
    table.LayTableId = reader.GetValue(3).ToString();// reader.GetValue(3).ToString(); 
    table.LayTeamId = reader.GetValue(4).ToString(); 
    alMainGrid.Add(table); 
    } 
    reader.Close(); 

    foreach (SupportTable table in alMainGrid) 
    { 
     //2nd 
     command.CommandText = String.Format("SELECT CTDesc FROM CutTable WHERE CTId ={0}", int.Parse(table.LayTableId)); 
     string tableDesc = (string)command.ExecuteScalar(); 
     table.LayTeamId = tableDesc; 

    //3rd-In this command.CommandText 
     command.CommandText = String.Format("SELECT TeamDesc FROM Team WHERE TeamId ={0}", int.Parse(table.LayTeamId)); 
     string teamDesc = (string)command.ExecuteScalar(); 
     table.LayTeamId = teamDesc; 
    } 
    dgvMain.DataSource = alMainGrid; 
+1

什麼是例外? –

+1

看起來像'table.LayTeamId'是一個空字符串或包含非數字字符。 – ekad

+2

順便說一句,你不應該連接字符串來形成你的查詢。這是讓自己容易受到SQL注入攻擊的好方法 –

回答

1

當你在該行指定table.LayTeamId幾行上面,你看到了異常:

table.LayTeamId = tableDesc; 

我希望tableDesc被分配一個值table.LayTeamId不能被解析到一個Int然後炸燬當您嘗試在這裏解析它:

command.CommandText = String.Format("SELECT TeamDesc FROM Team WHERE TeamId ={0}", int.Parse(table.LayTeamId)); 

注:

這是一個糟糕的方式,形成由連接字符串查詢。如果您不小心,這將使您容易受到SQL注入攻擊。在數據庫上執行查詢之前,請使用參數化查詢來清理查詢。

0

試試這個

command.CommandText = String.Format("SELECT CTDesc FROM CutTable WHERE CTId ={0}", (table.LayTableId == "") ? -1 : Convert.ToInt32(table.LayTableId); 


command.CommandText = String.Format("SELECT TeamDesc FROM Team WHERE TeamId ={0}", (table.LayTeamId == "") ? -1 : Convert.ToInt32(table.LayTeamId);