Ok I am using the code below in file called autocomplete.asmx (web service file) my main question is do I need to create a different web service for every field I want my auto complete to work for? IE maybe I would like to have the Company Name pulled out instead of country, but another time maybe name, now I know this just involves changing the select statement but How could I go about doing this so that depending on what field it is, it knows what select statement to use?
Thanks
public class AutoComplete : System.Web.Services.WebService
{
[WebMethod]
public string[] GetCountriesList(string prefixText)
{
DataSet dtst = new DataSet();
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
string strSql = "SELECT CountryName FROM Tbl_ooo WHERE CountryName LIKE '" + prefixText + "%' ";
SqlCommand sqlComd = new SqlCommand(strSql, sqlCon);
sqlCon.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter();
sqlAdpt.SelectCommand = sqlComd;
sqlAdpt.Fill(dtst);
string[] cntName = new string[dtst.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow rdr in dtst.Tables[0].Rows)
{
cntName.SetValue(rdr["CountryName"].ToString(), i);
i++;
}
}
catch { }
finally
{
sqlCon.Close();
}
return cntName;
}
}
Yes, you can use same webservice webmethod to populate country and company.
For that you want to use ContextKey property in ajax AutoCompleteExtender control
Below is the sample Code
Markup :
Search
<asp:TextBox ID="txtSearch" CssClass="textBlackBold" runat="server" Width="350px"></asp:TextBox>
<asp:DropDownList ID="ddlType" runat="server" AutoPostBack="True" onselectedindexchanged="ddlType_SelectedIndexChanged">
<asp:ListItem Value="0">Country</asp:ListItem>
<asp:ListItem Value="1">Companies</asp:ListItem>
</asp:DropDownList>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
EnableCaching="true" ContextKey="Products" UseContextKey="true"
TargetControlID="txtSearch" MinimumPrefixLength="1"
ServiceMethod="GetInfo" ServicePath="~/WebService.asmx" >
</asp:AutoCompleteExtender>
Code Behind C# Code :
protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
{
string strContextKey = "";
if(ddlType.SelectedValue.ToString() == "0")
strContextKey = "Country";
else
strContextKey = "Companies";
AutoCompleteExtender1.ContextKey = ddlType.SelectedItem.Text;
}
WebService Code :
[WebMethod]
public string[] GetInfo(string prefixText, string contextKey)
{
DataSet dtst = new DataSet();
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
string strSql = "";
if (contextKey == "Country")
{
strSql = "SELECT CountryName FROM Tbl_ooo WHERE CountryName LIKE '" + prefixText + "%' ";
}
else if(contextKey == "Companies")
{
strSql = //Other SQL Query
}
SqlCommand sqlComd = new SqlCommand(strSql, sqlCon);
sqlCon.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter();
sqlAdpt.SelectCommand = sqlComd;
sqlAdpt.Fill(dtst);
string[] cntName = new string[dtst.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow rdr in dtst.Tables[0].Rows)
{
cntName.SetValue(rdr[0].ToString(),i);
i++;
}
}
catch { }
finally
{
sqlCon.Close();
}
return cntName;
}
Related
I am trying fetch data from MySQL data base using store procedure in C#, To be more precise am following tri layer architecture am not sure where am wrong in the following below code i have tried in all the possibilities small help would be appreciated alot.
DataServices Layer
public DataSet FetchLoginDetails(string SchoolID)
{
object[] objparam = new object[1];
objparam[0] = new MySqlParameter
{
ParameterName = "#SchoolID",
DbType = System.Data.DbType.String,
Value =SchoolID
};
DataSet dsdataRes = ExecuteQuery("Storeprociduer", objparam);
return dsdataRes;
}
BusinessServices
private ITimeTableRepository ObjTimeTable
{
get { return UnityManager.Resolve<ITimeTableRepository>(); }
}
public DataSet FetchLoginDetails(string SchoolID)
{
return ObjTimeTable.FetchLoginDetails(SchoolID);
}
BusnessServices.Interfaces
public interface ITimeTableBO
{
DataSet FetchLoginDetails(string SchoolID);
}
UI .cs
public void LoadLoginDetails(DataSet ds)
{
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
ddlSubject.Items.Clear();
ListItem item1 = new ListItem();
item1.Text = "Choose a Subject";
item1.Value = "-1";
ddlSubject.Items.Add(item1);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
ListItem item = new ListItem();
item.Text = ds.Tables[0].Rows[i]["UserName"].ToString();
item.Value = ds.Tables[0].Rows[i]["UserName"].ToString();
ddlSubject.Items.Add(item);
}
}
Aspx code
<asp:DropDownList ID="ddlSubject" runat="server" Width="150px"
Height="27px" ClientIDMode="Static"
AutoPostBack="true" >
<asp:ListItem Value="-1" Text="Choose a Subject"></asp:ListItem>
</asp:DropDownList>
Store Procidure
CREATE DEFINER=`root`#`localhost` PROCEDURE `Storeprociduer`(
SchoolID
VARCHAR(255)
)
BEGIN
select UserName from scoolage_login where SchoolID =
SchoolID ;
END
Without looking at the other details of your code, I am assuming you are unable to connect and retrieve data from your MySQL database. Take a look at the MySqlCommand Object. There are code examples as well:
https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-sql-command.html
Try something like this:
using (MySqlConnection con = new MySqlConnection(yourConnectionString))
{
using (MySqlCommand cmd = new MySqlCommand("Storeprociduer", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#SchoolID", SchoolID);
using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
// Do something with results
}
}
}
See this SO question as well:
calling mysql storedprocedure from c#?
In my project I am using autocomplete extender.using this I am selecting only one item.But I want to select multiple items.what I should I do.please help me. below is my code:
aspx page:
<asp:TextBox ID="TextBox1" runat="server" CssClass="autosuggest ui-timepicker-input" Width="300px"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server" DelimiterCharacters=""
Enabled="True" ServiceMethod="GetListofCountries" MinimumPrefixLength="2" EnableCaching="true" CompletionSetCount="10" CompletionInterval="10" FirstRowSelected="false"
TargetControlID="TextBox1">
</ajaxToolkit:AutoCompleteExtender>
aspx.cs page:
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetListofCountries(string prefixText, int count)
{
//using (SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["con2"].ConnectionString))
//{
// sqlconn.Open();
// SqlCommand cmd = new SqlCommand("select UserEmail from [User] where Useremail like '%" + prefixText + "%'", sqlconn);
// cmd.Parameters.AddWithValue("#prefixText", prefixText);
// SqlDataAdapter da = new SqlDataAdapter(cmd);
// DataTable dt = new DataTable();
// da.Fill(dt);
// List<string> Emailid = new List<string>();
// for (int i = 0; i < dt.Rows.Count; i++)
// {
// Emailid.Add(dt.Rows[i]["UserEmail"].ToString());
// }
// return Emailid;
//}
List<string> customers = new List<string>();
using (SqlConnection conn = new SqlConnection())
{
List<string> terms = prefixText.Split(',').ToList();
terms = terms.Select(s => s.Trim()).ToList();
//Extract the term to be searched from the list
string searchTerm = terms.LastOrDefault().ToString().Trim();
//Return if Search Term is empty
if (string.IsNullOrEmpty(searchTerm))
{
// return
}
//Populate the terms that need to be filtered out
List<string> excludeTerms = new List<string>();
if (terms.Count > 1)
{
terms.RemoveAt(terms.Count - 1);
excludeTerms = terms;
}
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["con2"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
string query = "select UserEmail from [User] where Useremail like '%" + prefixText + "%'";
//Filter out the existing searched items
if (excludeTerms.Count > 0)
{
query += string.Format(" and UserEmail not in ({0})", string.Join(",", excludeTerms.Select(s => "'" + s + "'").ToArray()));
}
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#prefixText", prefixText);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
//customers.Add(string.Format("{0}-{1}", sdr["Userid"], sdr["CustomerId"]));
customers.Add(string.Format("{0}", sdr["UserEmail"]));
}
}
conn.Close();
}
return customers;
}
but it gives only one value.I want to select multiple items.please help me.
finally I got an answer for the above question.in the AutoCompleteExtender add DelimiterCharacters="," and ShowOnlyCurrentWordInCompletionListItem="true" . add this two items for the AutoCompleteExtender. It will work for me.if any one want this type of question, I hope this answer is help you,thats why I posted here.thank you.
im using asp.net and c#
im using 2 dropdownlist like dd1,dd2
how to fill 2nd dropdownlist dd2 by dd1 onselectindexchanged
my code is,
<asp:DropDownList ID="ddMedType" runat="server" CssClass="drop" AutoPostBack="true" OnSelectedIndexChanged="ddMedType_SelectedIndexChanged">
<asp:ListItem Value="0">-Select-</asp:ListItem>
<asp:ListItem Value="Tablet">Tablet</asp:ListItem>
<asp:ListItem Value="Tonic">Tonic</asp:ListItem>
<asp:ListItem Value="Capsules">Capsules</asp:ListItem>
<asp:ListItem Value="DispoTab">Disposable Tablet</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddMedName" runat="server" CssClass="drop" >
<asp:ListItem Value="0">-Select-</asp:ListItem>
</asp:DropDownList>
protected void ddMedType_SelectedIndexChanged(object sender, EventArgs e)
{
string MedType = ddMedType.SelectedItem.Text;
string str = "select MedicineName,MedicineId from MedicineMaster where MedicineType = '" + MedType + "'";
cmd = new SqlCommand(str, con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ddMedName.SelectedValue= reader["MedicineId"].ToString();
}
}
here the condition returns 2 items, but dropdownlist dd2 returns only 1 ...
You are setting the SelectedValue, this does not mean you're adding or removing items in your dropdownlist
DataTable medicines= new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("select MedicineName,MedicineId from MedicineMaster where MedicineType = '" + MedType + "'", con);
adapter.Fill(subjects);
ddMedName.DataSource = subjects;
ddMedName.DataTextField = "MedicineName";
ddMedName.DataValueField = "MedicineId";
ddMedName.DataBind();
}
catch (Exception ex)
{
// Handle the error
}
}
// Add the initial item - you can add this even if the options from the
// db were not successfully loaded
ddMedName.Items.Insert(0, new ListItem("-Select-", "0"));
You can also do it with the reader as follows:
ddMedName.Items.Clear();
ddMedName.Items.Add(new ListItem("-Select-", "0"));
while (reader.Read())
{
ddMedName.Items.Add(new ListItem(reader["MedicineName"].ToString(), reader["MedicineId"].ToString());
}
Try add item in the DropdownList..
DropDownList1.Items.Add(new ListItem(reader["MedicineId"].ToString(), reader["MedicineId"].ToString()));
Here is one solution may help you:
protected void ddMedType_SelectedIndexChanged(object sender, EventArgs e)
{
string MedType = ddMedType.SelectedItem.Text;
string str = "select MedicineName,MedicineId from MedicineMaster where MedicineType = '" + MedType + "'";
cmd = new SqlCommand(str, con);
SqlDataReader reader = cmd.ExecuteReader();
ddMedName.DataSource = reader;
ddMedName.DataTextField = "MedicineName";
ddMedName.DataValueField = "MedicineId";
ddMedName.DataBind();
}
I have a link button as follow
<asp:LinkButton ID="LinkButtonSearchClient" PostBackUrl="~/UI/clients.aspx" runat="server">Recherche </asp:LinkButton>
i want get a query string from it
<asp:LinkButton ID="LinkButtonSearchClient" PostBackUrl="~/UI/clients.aspx?id=12" runat="server">Recherche </asp:LinkButton>
and the id value comes from the source code
public string ID
{
get { return ViewState["id"]; }
}
To get the value on page load (in the backend .cs file) :
protected void Page_Load(object sender, EventArgs e)
{
var id = Request.QueryString["id"];
if (id != null)
{
// use id
}
}
Or you might want to put the id into the link (in the html) :
<asp:LinkButton ID="LinkButtonSearchClient" runat="server"
NavigateUrl='<%# String.Format("~/UI/clients.aspx?id={0}", Eval("ID"))%>'
Text='Recherche'></asp:LinkButton>
You probably do not need a postback, look here : PostbackUrl vs NavigateUrl
Try this,
public string ID
{
get { Request.QueryString["id"]; }
}
Edit : In your page load set your postback url like this, access postbackurl in server side
LinkButtonSearchClient.PostBackUrl = "~/UI/clients.aspx?id=" + this.ID;
See my following example :
in design as follow
<asp:HyperLink ID="HLink" runat="server"
NavigateUrl='<%#"Mobiles_Details.aspx?ID=" + Eval("ID") %>' Text='<%#
Bind("Name") %>' Height="70px" Width="200px" Font-Bold="true" Font-
Size="10pt" Font-Names="Times New Roman" />
In coding the class Mobiles_Details is:
public partial class Mobiles_Details : System.Web.UI.Page
{
public string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
Session["UserID"] = "100";
//int ID = 102;
int ID = Convert.ToInt32(Request.QueryString["ID"].ToString());
Session["Product_ID"] = ID;
if (Session["UserID"] == null || Session["UserID"].ToString() == string.Empty)
{
Response.Redirect("Login.aspx", false);
}
else
{
if (ID != null)
{
DataTable dt = Load_Items_ID(Convert.ToInt32(Session["UserID"].ToString()), ID);
lbl_Name.Text = dt.Rows[0]["Name"].ToString();
lbl_Price.Text = dt.Rows[0]["Price"].ToString();
lbl_Details.Text = dt.Rows[0]["Details"].ToString();
img_Product.ImageUrl = dt.Rows[0]["image"].ToString();
}
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('An Error has been occured ');" + ex.ToString(), true);
}
}
}
public DataTable Load_Items_ID(int UserID, int ID)
{
DataTable Returned_Value = new DataTable();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Products where UserID= " + UserID + " and Status='False' and ID =" + ID))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(Returned_Value);
}
}
}
}
return Returned_Value;
}
}
I create an autocomplete search box and I get product name and I want to get product photo but I did not do it. There is my code:
<asp:TextBox ID="txtContactsSearch" runat="server" Width="261"></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod="Search11"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="false"
CompletionSetCount="10"
TargetControlID="txtContactsSearch"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected = "true">
</cc1:AutoCompleteExtender>
Web Service Code:
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> Search11(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.AppSettings["U"].ToString();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Top(10) * from S WITH (NOLOCK) where KeySentences like #SearchText + '%' ";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> Search = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
//"<img src='st4.abc.com.tr/img/urun/p_" + sdr["RecID"].ToString()+"_01_01.jpg' />" + " "
Search.Add( sdr["KeySentences "].ToString().Substring(0, 30));
Search.Add("<img style = 'height:30px;width:30px' src = 'st4.abc.com.tr/img/urun/p_"+sdr["RecID"].ToString()+"_01_01.jpg'");
}
}
conn.Close();
return Search;
}
}
}
I can get product name but image is not. It seems:
I want to show only picture not HTML text.I think I use script or something like but I dont know What can I do for this? Thanks for your answers
the required functionality can be achieved by referring the following article
http://www.aspsnippets.com/Articles/Render-images-in-autocomplete-list-of-ASP.Net-AJAX-AutoCompleteExtender.aspx