Autocomplete in Ajax not working? - asp.net

In Ajax, i am using autocompleteExender in my asp.net application, i write the service for that, when i run that service it is working fine, when i place autocompleteextender in asp.net page and assign properity for ajax autocompleteextender it is not working. this is my code service:
[WebMethod]
public string[] GetCompletionList(string prefixText)
{
SqlConnection con=new SqlConnection
("server=******;database=Mydb;user id=***;password=****;");
string sql = "Select productname from F_Product
Where productname like '" + prefixText + "%'";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
try
{
DataTable dt = new DataTable();
da.Fill(dt);
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr[0].ToString(), i);
i++;
}
return items;
}
catch
{
return null;
}
finally
{
con.Close();
}
and this is my ajax autocompleteextender code.
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" MinimumPrefixLength="2"
TargetControlID ="TextBox1" ServiceMethod="GetCompletionList"
ServicePath="~/Autocomplete.asmx"
runat="server">
</asp:AutoCompleteExtender>
<asp:TextBox ID="TextBox1" runat="server"
Width="213px"></asp:TextBox>

Try this out.
[WebMethod]
public string[] GetCompletionList(string prefixText)
{
string sql = "Select productname from F_Product Where productname like #prefixText ";
SqlDataAdapter da = new SqlDataAdapter(sql, System.Configuration.ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString);
da.SelectCommand.Parameters.Add("#prefixText", SqlDbType.VarChar, 50).Value = prefixText + "%";
DataTable dt = new DataTable();
da.Fill(dt);
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr["productname"].ToString(), i);
i++;
}
return items;
}
If you find it useful, please mark it as your answer else let me know...

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Web.Script.Services;
namespace YourProject
{
/// <summary>
/// Summary description for WebService
/// </summary>
// [ScriptService]
//[System.Web.Script.Services.ScriptService()]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public string[] GetCompletionList(string prefixText)
{
string sql = "Select productname from F_Product Where productname like #prefixText ";
SqlDataAdapter da = new SqlDataAdapter(sql, System.Configuration.ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString);
da.SelectCommand.Parameters.Add("#prefixText", SqlDbType.VarChar, 50).Value = prefixText + "%";
DataTable dt = new DataTable();
da.Fill(dt);
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr["productname"].ToString(), i);
i++;
}
return items;
}
}
}
If you find it useful, please mark it your answer else let me know...

Related

how to trim the white spaces in the output of json webservice asp.net

Hi (I'm new to JSON this is my 1st webservice)
I have created an Webservice in asp.net that returns JSON data.Every thing works fine but what i need is when fetching the data from the database it should trim the white spaces before it displays.
Because in my data base i have given the field type as nvarchar(100) but inserted the text with <20 characters so in the output i'm getting the result with whitespaces also
For eg:
{"Cargo":[{"Id":1,"FirstName":"devi ","LastName":"priya ","Contactno":"965577796 "}]}
after the name devi and priya there is lots if spaces.
But the actual result i supposed to get is;
{"Cargo":[{"Id":1,"FirstName":"devi","LastName":"priya ","Contactno":"965577796 "}]}
Here is my code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
namespace Webservice
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
public Service1()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
//public string GetEmployees(string SearchTerm)
public void GetEmployees()
{
try
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM Contact e ";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(dt);
con.Close();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow rs in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, rs[col]);
}
rows.Add(row);
}
//return serializer.Serialize(rows);
//return "{ \"Cargo\": " + serializer.Serialize(rows) + "}";
//JavaScriptSerializer js = new JavaScriptSerializer();
//string strJSON = js.Serialize(new { Cargo = rows });
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serializer.Serialize(new { Cargo = rows }));
//return serializer.Serialize(new { Cargo = rows });
}
catch (Exception ex)
{
//return errmsg(ex);
}
}
}
can any one please help me.
thanks in advance.
hi the following code helps me to trim the white spaces:
row.Add(col.ColumnName, rs[col].ToString().Trim());

Need to change the format of data return from JSON

I'm creating a webservice which should get data from database(sql server) and return it.
Every thing working fine. But what I need is I need to display the data with the format which I needed.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
namespace Webservice
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
public Service1()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
// public string GetEmployees(string SearchTerm)
public string GetEmployees()
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "SELECT * FROM Contact e WHERE FirstName LIKE '%" + SearchTerm + "%'";
cmd.CommandText = "SELECT * FROM Contact e ";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(ds);
con.Close();
// Create a multidimensional array
string[][] EmpArray = new string[ds.Tables[0].Rows.Count][];
int i = 0;
foreach (DataRow rs in ds.Tables[0].Rows)
{
//EmpArray[i] = new string[] { rs["FirstName"].ToString(), rs["LastName"].ToString(), rs["Contactno"].ToString() };
EmpArray[i] = new string[] { "FNAME: " + rs["FirstName"].ToString(), "LName: " + rs["LastName"].ToString(), "Contactno: " + rs["Contactno"].ToString()};
i = i + 1;
}
// Return JSON data
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(EmpArray);
return strJSON;
}
catch (Exception ex) { return errmsg(ex); }
}
public string errmsg(Exception ex)
{
return "[['ERROR','" + ex.Message + "']]";
}
}
}
Here is my output:
[["FNAME: devi","LName: priya ","Contactno: 965577796 "],
["FNAME: arun","LName: kumar ","Contactno: 9944142109"],
["FNAME: karu ","LName: ronald","Contactno: 8883205008"]]
But I need the result in the following format:(which should contain curly braces and the word cargo at starting each name and value should start and end with double codes..
{ "Cargo": [ { "FNAME": "devi", "LName": "priya " },
{"FNAME": "arun", "LName": "kumar" }, { "FNAME": "karu ", "LName": "ronald" }] }
The followiing code solves my problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
[ToolboxItem(false)]
public class CService : System.Web.Services.WebService
{
public CService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
//public string GetEmployees(string SearchTerm)
public void CargoNet()
{
try
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT TOP 1 * FROM cargo_tracking ";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(dt);
con.Close();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow rs in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, rs[col].ToString().Trim());
}
rows.Add(row);
}
//return serializer.Serialize(rows);
//return "{ \"Cargo\": " + serializer.Serialize(rows) + "}";
//JavaScriptSerializer js = new JavaScriptSerializer();
//string strJSON = js.Serialize(new { Cargo = rows });
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serializer.Serialize(new { Cargo = rows }));
//return serializer.Serialize(new { Cargo = rows });
}
catch (Exception ex)
{
//return errmsg(ex);
}
}
public string errmsg(Exception ex)
{
return "[['ERROR','" + ex.Message + "']]";
}
}

how to ignore default value(string) in the output of Json webservice

I need to neglect the default value(*string *) in the output which is displayed when executing the webservice JSON.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
namespace Webservice
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
public Service1()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
//public string GetEmployees(string SearchTerm)
public string GetEmployees()
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM Contact e ";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(dt);
con.Close();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow rs in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, rs[col]);
}
rows.Add(row);
}
return "{ \"Cargo\": " + serializer.Serialize(rows) + "}";
}
public string errmsg(Exception ex)
{
return "[['ERROR','" + ex.Message + "']]";
}
}
}
Output is;
<string>
{ "Cargo": [{"Id":1,"FirstName":"devi","LastName":"priya ","Contactno":"965577796 "},{"Id":2,"FirstName":"arun","LastName":"kumar","Contactno":"9944142109"},{"Id":3,"FirstName":"karu","LastName":"ronald","Contactno":"8883205008"}]}
</string>
But the actual output i need is;
{ "Cargo": [{"Id":1,"FirstName":"devi","LastName":"priya ","Contactno":"965577796 "},{"Id":2,"FirstName":"arun","LastName":"kumar","Contactno":"9944142109"},{"Id":3,"FirstName":"karu","LastName":"ronald","Contactno":"8883205008"}]}
In the above output i dont want to see the string /string
is there is a way to omit that if so please suggest me.
Thanks in advance
Try replacing return "{ \"Cargo\": " + serializer.Serialize(rows) + "}"; with return serializer.Serialize(new { Cargo = rows });
Your question can be found here:
ResponseFormat.Json returns xml
And try to use this http://www.nuget.org/packages/Newtonsoft.Json/
it can be very helpful to deal with JSON.
Good Luck.

SQL Connection variable not in the current context

I am a beginner in.NEt and having difficulty using the sql connection in a radio button index changed eventhandler that i defined on the page_load.
Below is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace Controls
{
public partial class Report_Selection : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.HeaderStyle.Font.Bold = true;
RadioButtonList1.SelectedIndexChanged += new EventHandler(RadioButtonList1_SelectedIndexChanged);
using (SqlConnection cnn = new SqlConnection("Data Source=DBSW9079;Initial Catalog=Underwriting;Integrated Security=SSPI;"))
{
SqlCommand cmd;
SqlDataReader sdr;
if (!IsPostBack)
{
cmd = new SqlCommand("select Categoryid,CategoryTitle from Report_Category", cnn);
cnn.Open();
sdr = cmd.ExecuteReader();
SelectCategorydlist1.DataSource = sdr;
SelectCategorydlist1.DataTextField = "CategoryTitle";
SelectCategorydlist1.DataValueField = "categoryid";
SelectCategorydlist1.DataBind();
cnn.Close();
}
else
{
//It's a Post back
//make the grid visible and fill it
GridView1.Visible = true;
RadioButtonList1.SelectedValue = "1";
cmd = new SqlCommand("Select rptdesc,rptdesctext,categoryid from report_description " + "where categoryid != 99999"
+ "and categoryid = " + Convert.ToInt32(SelectCategorydlist1.SelectedValue).ToString(), cnn);
cnn.Open();
sdr = cmd.ExecuteReader();
GridView1.DataSource = sdr;
GridView1.DataBind();
sdr.Close();
{
}
}
}
}
void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd1;
SqlDataReader sdr1;
if (RadioButtonList1.SelectedIndex.Equals(1))
{
RadioButtonList1.ClearSelection();
cmd1 = new SqlCommand("Select rptdesc,rptdesctext,categoryid from report_description "
+ "and categoryid = " + Convert.ToInt32(SelectCategorydlist1.SelectedValue).ToString(), cnn);
cnn.Open();
sdr1= cmd1.ExecuteReader();
GridView1.DataSource = sdr1;
GridView1.DataBind();
sdr1.Close();
}
}
}
}
In the above code when i use the cnn sequel connection in the event handler i get an small r
Your query in RadioButtonList1_SelectedIndexChanged appears to be incorrect. There's an and without a where:
Select rptdesc,rptdesctext,categoryid from report_description
and categoryid = ...
^^^ should be WHERE

Asp.net how to correct the error

I'm designing in my web page and image are stored in my database (The project is Photostudio management system)
MY Code:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace photoshops
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection cnn = new SqlConnection();
DataSet ds = new DataSet();
string constr = null;
SqlCommand cmd = new SqlCommand();
if (IsValid != true )
{
constr = #"Data Source=DEVI\SQLEXPRESS;Initial Catalog =cat; Integrated
Security=SSPI";
cnn.ConnectionString = constr;
try
{
if (cnn.State != ConnectionState.Open)
cnn.Open();
}
catch (Exception ex)
{
string str1 = null;
str1 = ex.ToString();
}
cmd.Connection = cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "photoset";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#BillNo", TextBox1.Text);
cmd.Parameters.AddWithValue("#CustomerName", TextBox2.Text);
cmd.Parameters.AddWithValue("#Address", TextBox3.Text);
cmd.Parameters.AddWithValue("#StartDate",Rdbsdate.SelectedDate );
cmd.Parameters.AddWithValue("#EndDate", Rdbddate.SelectedDate );
SqlParameter param0 = new SqlParameter("#Systemurl", SqlDbType.VarChar,
50);
cmd.Parameters.AddWithValue("#Numberofcopies", TextBox7.Text);
cmd.Parameters.AddWithValue("#Amount", TextBox8.Text);
cmd.Parameters.AddWithValue("#Total", TextBox9.Text);
da.SelectCommand = cmd;
try
{
da.Fill(ds);
}
catch (Exception ex)
{
string strErrMsg = ex.Message;
//throw new applicationException("!!!! An error an occured while
//inserting record."+ex.Message)
}
finally
{
da.Dispose();
cmd.Dispose();
cnn.Close();
cnn.Dispose();
}
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
Msg.Text = "Photo setting sucessfullY";
}
else
{
Msg.Text = "photosetting failled";
}
}
}
}
}
}
My ERROR
The record are not stored and image is not stored how to change in my code .
Well first of all, you're not saving the image, you're saving the path of your computer.
You need to save the byte array of the photo.
In short:
Upload its the upload control where you select the image
pic its the byte arrey where you upload the binary content of the photo
and then you only send it as a simple parameter cmd.Parameters.Add ("#pic", pic);
public void OnUpload(Object sender, EventArgs e)
{
// Create a byte[] from the input file
int len = Upload.PostedFile.ContentLength;
byte[] pic = new byte[len];
Upload.PostedFile.InputStream.Read (pic, 0, len);
// Insert the image and comment into the database
SqlConnection connection = new
SqlConnection (#"server=INDIA\INDIA;database=iSense;uid=sa;pwd=india");
try
{
connection.Open ();
SqlCommand cmd = new SqlCommand ("insert into Image "
+ "(Picture, Comment) values (#pic, #text)", connection);
cmd.Parameters.Add ("#pic", pic);
cmd.Parameters.Add ("#text", Comment.Text);
cmd.ExecuteNonQuery ();
}
finally
{
connection.Close ();
}
}
here are some tutorials, the first link it's very straightforward and the code its simple
http://www.codeproject.com/KB/web-image/PicManager.aspx
another, just in case:
http://www.redmondpie.com/inserting-in-and-retrieving-image-from-sql-server-database-using-c/
Principal resource: http://www.codeproject.com/KB/web-image/PicManager.aspx

Resources