Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to serialize and send a json string back to an Ajax function. I am getting an error in:
C#
dt = ds.Tables[0];


C#
[System.Web.Services.WebMethod]
        public static string GetJSONdata(string id1)
        {
            DataSet ds;
            string connStr = ConfigurationManager.ConnectionStrings["jsonobject"].ConnectionString;
            string cmdStr = "SELECT ([datetime],[col1],[col2],[col3]) FROM [jsondata] WHERE [idd]=@idd;";
            try
            {
                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
                    {
                        conn.Open();
                        cmd.Parameters.AddWithValue("@idd", id1);
                        cmd.ExecuteNonQuery();
                        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                        {
                            da.Fill(ds);
                            dt = ds.Tables[0];
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            var json2 = serializer.Serialize(rows);
            return json2;
        }
Posted

1 solution

Change the code...
C#
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
    da.Fill(ds);
    dt = ds.Tables[0];
}

To...
C#
DataTable dt = null;

using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
    da.Fill(ds);
}

if(ds != null && ds.Tables != null && ds.Tables.Count > 0)
{
    dt = ds.Tables[0];
}

Now check if dt is null or not. If not null, then proceed and serialize that.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900