2013-07-30 5 views
0

이것은 내 머리를 긁적이다.String.Format 오류를 반환

나는 자동 완성 제어를위한 JSON과 같은 데이터를 포함하는 문자열을 반환하는 기능을 가지고 있지만, String.Format가 동작하지 않습니다 :

private string GetUsers(string crit) 
{ 
    string result = ""; 

    using (DataTable dt = dl.GetRecordSet("select ob_id, ob_desc from objects where ac_id = @acid and ob_desc like @crit and ot_id = 29 and ob_deleted = 0 order by ob_desc", new[] { MyApplicationSession.AccountId, "%" + crit + "%" })) 
    { 
     result = "[ "; 
     foreach (DataRow dr in dt.Rows) 
     { 
      result += string.Format("{ \"id\": \"{0}\", \"label\": \"{1}\", \"value\": \"{1}\" },", dr["ob_id"].ToString(), dr["ob_desc"].ToString()); 
     } 

     result = result.Substring(0, result.Length - 1); // remove trailing comma 
     result += "]"; 
    } 
    return result; 
} 

난 항상 오류 "Input string was not in a correct format."를받을 수 있습니다.

dr["ob_id"].ToString()은 정수이고 dr["ob_desc"].ToString()은 SQL Server 2008 데이터베이스의 varchar입니다.

Visual Studio에서는 "문자열을 DateTime으로 변환 할 때 ..."라는 문제 해결 팁에서 해당 문자열의 위치를 ​​알 수 없습니다.

\ "와 (과) 바꾸기", "\"를 ""로 바꾸고 (문자열) 매개 변수를 명시 적으로 캐스팅하는 등의 변형을 시도했습니다.

내가 찾은 유일한 것은 값을 문자열에 직접 넣고 string.Format을 생략하는 것입니다.

답변

5

거기에 여분의 중괄호가있어 파서를 혼란스럽게합니다. {{처럼 탈출 : 당신은 출력 실제 중괄호로, String.Format에, {...}에 전체 문자열을 이탈 한

string.Format("{{ \"id\": \"{0}\", \"label\": \"{1}\", \"value\": \"{1}\" }},", ... 

(Related)

+0

뒤늦은 암시에서 맹목적으로 ... 고맙습니다. –

0

, 당신과 같이 {{}}을 수행해야합니다

result += string.Format("{{ \"id\": \"{0}\", \"label\": \"{1}\", \"value\": \"{1}\" }},", dr["ob_id"].ToString(), dr["ob_desc"].ToString());