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.
Related
i would like to create an id generator based on their department selected from the dropdownlist. lets say my ddl has 3 departments (A,B,C) and when generating an id it will be A20181001 and then A20181002 upon submission but when i pick B from the ddl after sending A20181001 to the database, it will be B20181001.
so far i have created the code for the increment for the id without the departments. here is the code i did so far. (I used the date for today so the 20181001 is just an example):
void getMRF_No()
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
int mrf = 0;
int i;
string a;
//string x = Request.QueryString["BUnit"];
string mrfNo = "";
database db = new database();
string conn = dbe.BU();
SqlConnection connUser = new SqlConnection(conn);
SqlCommand cmd = connUser.CreateCommand();
SqlDataReader sdr = null;
string query = "SELECT TOP 1 MRF_NO FROM incMRF ORDER BY MRF_NO DESC";
connUser.Open();
cmd.CommandText = query;
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr.GetInt32(0).ToString();
}
if (mrfNo == "")
{
mrfNo = Convert.ToString(year) + "" + 00;
}
mrf += 0;
i = Convert.ToInt32(mrfNo) + 1;
a = i.ToString();
txtMRFNo.Text = a;
connUser.Close();
}
any help to improve this code will be helpful. thank you :)
EDIT:
here is the dropdown list code:
void SelectBU()
{
string database = dbe.BU ();
using (SqlConnection con = new SqlConnection(database))
{
con.Open();
string query = "select BUnit from BusinessUnit";
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
DataSet ds = new DataSet();
sda.Fill(ds, "BUnit");
ddlBu.DataSource = ds;
ddlBu.DataTextField = "BUnit";
ddlBu.DataValueField = "BUnit";
ddlBu.DataBind();
selectOption(ddlBu, "Select Dept");
}
con.Close();
}
}
EDIT2: I will state what im searching for here incase some doesnt know or understand. What i want is upon selecting a department from a dropdownlist, for example i picked A. the textbox show show A2018102201. if i select B it should show B2018102201 and if its C then c2018102201. and it will change its number once i submit it to a database and a new form loads. So if A2018102201 is already in the database, then the text shown in the text box will be A2018102202. BUT if i select B then the textbox will show B2018102201 since it does not exist in the database yet.
First you should get max ID, then increase the numeric part of your Id, and If this is a multi-user application, you have to lock your table, because it might create many ID duplication, Therefore I'm not recommend to create ID like this on c#, it is better to create a Sequence on SQL server. but I wrote this sample for you, just call it with proper value.
static string getMRF_No(string prefixCharFromDropDownList)
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
string mrfNo = "";
SqlConnection connUser = new SqlConnection("Server=130.185.76.162;Database=StackOverflow;UID=sa;PWD=$1#mssqlICW;connect timeout=10000");
SqlCommand cmd = new SqlCommand(
$"SELECT MAX(MRF_NO) as MaxID FROM incMRF where MRF_NO like '{prefixCharFromDropDownList}%'"
,connUser
);
connUser.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr["MaxID"].ToString();
}
if (mrfNo == "")
{
mrfNo = prefixCharFromDropDownList + year + "000";
}
else
{
mrfNo = prefixCharFromDropDownList + (long.Parse(mrfNo.Substring(1)) + 1).ToString().PadLeft(2);
}
sdr.Close();
cmd = new SqlCommand($"INSERT INTO incMRF (MRF_NO) values ('{mrfNo}')",connUser);
cmd.ExecuteNonQuery();
connUser.Close();
//txtMRFNo.Text = prefixCharFromDropDownList + i.ToString();
return mrfNo;
}
I call this method on a console application as test.
static void Main(string[] args)
{
// send dropdown (selected char) as prefix to method
var newAId = getMRF_No("A");
var newAnotherAId = getMRF_No("A");
var newBId = getMRF_No("B");
var newAnotherAId2 = getMRF_No("A");
Console.ReadKey();
}
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
I am trying to format the text of my drop down list but nothing seems to work. Here is my code below:
Drop down list:
<asp:DropDownList runat="server" ID="ddlSalary" CssClass="ddlBox"
CausesValidation="true" AutoPostBack="true"
onselectedindexchanged="ddlSalary_SelectedIndexChanged" />
Code behind:
if (!IsPostBack)
{
ddlSalary.DataSource = Placements.DropDownPopulating("Placement_Salary_From");
ddlSalary.DataBind();
ddlSalary.Items.Insert(0, new ListItem("-- Salary --", "0"));
Results:
6.0000
200.0000
1000.0000
But I would like:
£6
£200
£1000
I have tried using:
ddlSalary.DataTextFormatString = "{0:C}";
EDIT
Populating drop down list:
public static List<string> DropDownPopulating(string selectedFilter)
{
List<string> returnVal = new List<string> { };
using (SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["websiteContent"].ConnectionString))
{
sqlCon.Open();
string SQL = "SELECT DISTINCT " + selectedFilter + " FROM Placements";
using (var CMD = new SqlCommand(SQL, sqlCon))
{
using (var DR = CMD.ExecuteReader())
{
while (DR.Read())
{
returnVal.Add(DR[selectedFilter].ToString());
}
}
}
sqlCon.Close();
}
return returnVal;
}
You should use a numeric datatype if you want the formatting to work:
public static List<T> DropDownPopulating<T>(string selectedFilter)
{
var returnVal = new List<T>();
var connectionString = ConfigurationManager.ConnectionStrings["websiteContent"].ConnectionString;
using (var con = new SqlConnection(connectionString))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "SELECT DISTINCT " + selectedFilter + " FROM Placements";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// if you are using .NET 4.5
returnVal.Add(reader.GetFieldValue<T>(reader.GetOrdinal(selectedFilter)));
// if you are using .NET 4.0 or older:
// returnVal.Add((T)reader.GetValue(reader.GetOrdinal(selectedFilter)));
}
}
}
return returnVal;
}
and then:
ddlSalary.DataSource = Placements.DropDownPopulating<decimal>("Placement_Salary_From");
ddlSalary.DataTextFormatString = "{0:C}";
ddlSalary.DataBind();
use this query to get data.....
select '$'+Cast((Cast(Price as int))as varchar) from TableName
I want to make a search like them from google.
I've made it this far, that I can show all data from the database in my textbox with using a webservice. Thats my code:
Webform.aspx
<%--**Start Search**--%>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services><asp:ServiceReference Path="~/WebService.asmx" /></Services>
</asp:ScriptManager>
<%--Search-Textbox--%>
<asp:TextBox runat="server" ID="txtSearchInput" Width="100%" />
<asp:Button ID="btnSearch" runat="server" Text="Suche" onclick="btnSearch_Click" />
<%--Autocomplete (Ajax)--%>
<asp:AutoCompleteExtender ID="AutoComplete1" runat="server" TargetControlID="txtSearchInput"
ServiceMethod="GetNames" ServicePath="~/WebService.asmx" MinimumPrefixLength="1"
EnableCaching="true" CompletionInterval="1000" CompletionSetCount="20">
</asp:AutoCompleteExtender>
<%--**End Search**--%>
Webservice.asmx
[WebMethod]
public string[] GetNames(string prefixText, int count)
{
List<string> items = new List<string>(count);
DataSet ds = new DataSet();
string cs = ConfigurationManager.ConnectionStrings["CSLinker"].ConnectionString;
using (SqlConnection connection = new SqlConnection(cs))
{
string sql = "SELECT Name FROM tabProjects WHERE Name LIKE '" + prefixText + "%' UNION all SELECT Name FROM tabLinks WHERE Name LIKE '" + prefixText + "%'";
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(sql, connection);
adapter.Fill(ds);
}
foreach (DataRow dr in ds.Tables[0].Rows)
{
items.Add(dr["Name"].ToString());
}
return items.ToArray();
}
My problem now is, that i only have the name from the database. But for the search I need also the ID. Can somebody say me, how I can also query the ID without showing it in the textform?
I hope you can understand my problem. My english isnt' so good...
Thanks for helping!
Why not just pass the project name as the parameter rather than the probject ID? If you are using Response.Redirect I am assuming the user selects a project from the list of selections and the code behind handles somekind of event:
public void onProjectSelected()
{
string cs = ConfigurationManager.ConnectionStrings["CSLinker"].ConnectionString;
string projectName = txtSearchInput.Text;
int projectID = 0;
using (SqlConnection connection = new SqlConnection(cs))
{
using (SqlCommand command = new SqlCommand("SELECT ProjectID FROM TabProjects WHERE Name = #Name", connection))
{
command.Parameters.Add(new SqlParameter("#Name", SqlDbType.VarChar, 50)).Value = projectName;
connection.Open();
if (int.TryParse(command.ExecuteScalar().ToString(), out projectID))
{
Response.Redirect(string.Format("?ProjectID={0}", projectID));
}
connection.Close();
}
}
//Handle project not found events here
}
Also USE PARAMATERISED QUERIES otherwise SQL Injection could ruin your day!
If I were to type "It's a test" into your text box you would end up with an invalid SQL statement as the apostrophe I have used will result in the following SQL.
SELECT Name FROM tabProjects WHERE Name LIKE 'It's a test%'
Which clearly won't run and will not be a great user experience for anyone using your website. More seriously though, if I were to type into the text box on your page '; DROP TABLE TabProjects -- you may find, depednding on the permissions assigned to the CSLinker connection string, that you no longer have an tabProjects table as this is the SQL that is run:
SELECT Name FROM tabProjects WHERE Name LIKE ''; DROP TABLE tabProjects -- %'
You should use something like this for your web method:
[WebMethod]
public string[] GetNames(string prefixText, int count)
{
List<string> items = new List<string>();
string cs = ConfigurationManager.ConnectionStrings["CSLinker"].ConnectionString;
using (SqlConnection connection = new SqlConnection(cs))
{
using (SqlCommand command = new SqlCommand("SET ROWCOUNT #Count SELECT Name FROM TabProjects WHERE Name LIKE #Name + '%'", connection))
{
command.Parameters.Add(new SqlParameter("#Name", SqlDbType.VarChar, 50)).Value = prefixText;
command.Parameters.Add(new SqlParameter("#Count", SqlDbType.Int, 8)).Value = count;
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
items.Add(reader.GetString(0));
}
}
connection.Close();
}
}
return items.ToArray();
}
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;
}