Question

This has me scratching my head.

I have a function that returns a string containing json-like data for an autocomplete control, but can't get String.Format to work:

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;
}

I always receive the error "Input string was not in a correct format.".

dr["ob_id"].ToString() is an integer and dr["ob_desc"].ToString() is a varchar in the SQL Server 2008 database.

Visual Studio also advises under Troubleshooting Tips that "When converting a string to DateTime...", no idea where it gets that from.

I have tried variations such as replacing \" with ', replacing \" with "" and explicitly casting the parameters as (string).

The only thing I find to work is putting the values directly in the string and omitting string.Format.

Was it helpful?

Solution

You've got some extra curly-brackets in there, which confuses the parser. Escape them like {{:

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

(Related)

OTHER TIPS

You have encased your entire string in {...}, in String.Format, to output an actual curly brace, you need to do {{ and }} like so:

result += string.Format("{{ \"id\": \"{0}\", \"label\": \"{1}\", \"value\": \"{1}\" }},", dr["ob_id"].ToString(), dr["ob_desc"].ToString());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top