Call method values on page behind - asp.net

i have this method in mail.cs file which take one parameter,call store procedures and and return values from database.
public void select(string type)
{
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("EmailSetup_CRUD"))
{
cmd.Parameters.AddWithValue("#Action", "SELECT");
cmd.Parameters.AddWithValue("#Type", type);
}
}
}
i want to call the return values from this method on page behind and bind it with label. please advice how to do it.
on my page behind on page load i have done like this
mail callmail = new mail()
now i label1.text how to assign return value to label1.text.
method returns 5 column and i have 5 label on my page so each column will assign to each label.

As per the discussion and assumptions I made following code
mail.cs
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace tempApp4
{
public class mail
{
public DataTable select(string type)
{
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("EmailSetup_CRUD", con))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "SELECT");
cmd.Parameters.AddWithValue("#Type", type);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
return dataSet.Tables[0];
}
}
}
}
}
WebForm1.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="tempApp4.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="label1" runat="server" />
<asp:Label ID="label2" runat="server" />
<asp:Label ID="label3" runat="server" />
<asp:Label ID="label4" runat="server" />
<asp:Label ID="label5" runat="server" />
</form>
</body>
</html>
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace tempApp4
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
mail mail = new mail();
var table = mail.select("TYPE_VALUE");
label1.Text = Convert.ToString(table.Rows[0][0]);
label2.Text = Convert.ToString(table.Rows[0][1]);
label3.Text = Convert.ToString(table.Rows[0][2]);
label4.Text = Convert.ToString(table.Rows[0][3]);
label5.Text = Convert.ToString(table.Rows[0][4]);
}
}
}
SqlDataAdapter "adapter" used to fetch records from the DB and fill it in dataSet. Data set holds many table as your procedure returns single table the "select" method returns single table at the end as:
return dataSet.Tables[0];
Thus "select" method have return type as "DataTable". Then finally access returned value in code behind using mail class's object and filling the labels by accessing the column as follows:
label1.Text = Convert.ToString(table.Rows[0][0]);
The first 0 in "table.Rows[0][0]" is for rows and second is for column. For column optionally you can specify name of the column as:
label1.Text = Convert.ToString(table.Rows[0]["COLUMN_NAME"]);
Since I don't know the column names I am using indexing.
Hope it helps

Related

Allow sending email to multiple recipients in ASP.NET with loop and database

I am using ASP.NET and SQL Server to send email to multiple recipients with loop. But there is an error here. I have find my solution from internet but still can't solve it.
Here is the error shown:
var toAddress = mm.To.Add(email);
Here is my .aspx file code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="push_notification_admin.aspx.cs" Inherits="Assignment.push_notification_admin" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function alertme() {
Swal.fire(
"The Email Successfully Sent!" ,
'success'
)
}
</script>
<style>
.error {
color: red;
background-image: url("../images/error.png");
background-repeat: no-repeat;
padding-left: 20px;
font-size: 12px;
}
.auto-style1 {
height: 33px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Push Notification:</h2>
<div>
<table style="width: 100%;">
<tr>
<td> <asp:Label ID="Label2" runat="server" Text="Subject"></asp:Label></td>
<td> <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please enter subjuct!" ControlToValidate="TextBox1" CssClass="error" Display="Dynamic"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style1"><asp:Label ID="Label1" runat="server" Text="Content"></asp:Label></td>
<td class="auto-style1"><asp:TextBox ID="TextBox2" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter content!" ControlToValidate="TextBox2" CssClass="error" Display="Dynamic"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td> <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /></td>
</tr>
</table>
</div>
</div>
</form>
</body>
</html>
Here is my aspx.cs file 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;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Net.Configuration;
using System.Collections.Specialized;
using System.Configuration;
using System.Net;
using System.Collections;
using System.Net.Security;
namespace Assignment
{
public partial class push_notification_admin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string strcon = ConfigurationManager.ConnectionStrings["Database1ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("SELECT * from Notification", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader reader;
con.Open();
reader = cmd.ExecuteReader();
ArrayList emailArray = new ArrayList();
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
while (reader.Read()){
emailArray.Add(reader["Notice_email"]);
}
foreach (string email in emailArray) {
using (MailMessage mm = new MailMessage(smtpSection.From, "sender#gmail.com"))
{
// Gmail Address from where you send the mail
var fromAddress = "inpuzzle2021#gmail.com";
// any address where the email will be sending
var toAddress = mm.To.Add(email);
//Password of your gmail address
const string fromPassword = "inpuzzlepwd";
// Passing the values and make a email formate to display
string subject = TextBox1.Text.ToString();
string body = TextBox2.Text.ToString();
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);
}
}
reader.Close();
con.Close();
}
}
}
I will be appreciate if someone could help me to solve this problem.
Add method of mm.To is void. i.e. the method returns nothing and hence you cannot assign it to a variable. so your code should be just mm.To.Add(email);. This should fix the error you see.
Here is the latest coding and I have solve it!
The coding that I change to fix it are:
emailArray.Add(reader["Notice_email"].ToString());
and
var toAddress = email;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Net.Configuration;
using System.Collections.Specialized;
using System.Configuration;
using System.Net;
using System.Collections;
using System.Net.Security;
namespace Assignment
{
public partial class push_notification_admin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string strcon = ConfigurationManager.ConnectionStrings["Database1ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("SELECT * from Notification", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader reader;
con.Open();
reader = cmd.ExecuteReader();
ArrayList emailArray = new ArrayList();
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
while (reader.Read()){
emailArray.Add(reader["Notice_email"].ToString());
}
foreach (string email in emailArray) {
using (MailMessage mm = new MailMessage(smtpSection.From, "sender#gmail.com"))
{
// Gmail Address from where you send the mail
var fromAddress = "inpuzzle2021#gmail.com";
// any address where the email will be sending
var toAddress = email;
//Password of your gmail address
const string fromPassword = "inpuzzlepwd";
// Passing the values and make a email formate to display
string subject = TextBox1.Text.ToString();
string body = TextBox2.Text.ToString();
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);
}
}
reader.Close();
con.Close();
}
}
}

How to save and retrieve image from database in ASP.NET

I want to show image in image control on page load. I'm using the following code. My problem is that the image is saved in the database as binary data, but I can't retrieve the image in the image control
public partial class TeacherProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
profilepic();
}
protected void upload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
HttpPostedFile file = FileUpload1.PostedFile;
Byte[] imgbyte = new Byte[file.ContentLength];
file.InputStream.Read(imgbyte, 0, file.ContentLength);
SqlCommand cmd = new SqlCommand("Update Registration set Photo = '" + imgbyte + "' where id ='" + idd.Text + "' ", con);
//cmd.Parameters.AddWithValue("#userid", 222); //image id
//cmd.Parameters.AddWithValue("#pic", imgbyte);
//try
//{
con.Close();
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "Image Uploaded";
con.Close();
//}
//catch
//{
// Label1.Text = "Try Again";
//}
}
}
public void profilepic()
{
SqlCommand cmd2 = new SqlCommand("select Photo from Registration where Username = '" + username1.Text + "'", con);
//cmd2.Parameters.AddWithValue("#userid", username1.Text);
con.Open();
SqlDataReader dr = cmd2.ExecuteReader();
if (dr.Read())
{
byte[] bytes = (byte[])dr["Photo"];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
Image1.ImageUrl = "data:image/png;base64," + base64String;
cmd2.ExecuteNonQuery();
con.Close();
}
else
{
}
}
}
Can anybody help me please?
Thanks in advance...
my code for file upload
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="fileUpload.aspx.cs" Inherits="fetchImage.fileUpload" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
margin-left: 0px;
}
.auto-style2 {
margin-left: 6px;
margin-top: 0px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<div>
<asp:TextBox ID="TextBox1" runat="server" CssClass="auto- style1"></asp:TextBox>
<asp:Button ID="Button1" runat="server" CssClass="auto-style2" OnClick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
file upload cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace fetchImage
{
public partial class fileUpload : System.Web.UI.Page
{
string path;
SqlConnection con = new SqlConnection("Data Source=DESKTOP- U0NOKBP\\SQLEXPRESS;Initial Catalog=Lnmi;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
FileUpload1.SaveAs(Request.PhysicalApplicationPath + "/Images/"+ FileUpload1.FileName.ToString());
path = "Images/"+FileUpload1.FileName.ToString();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Images values('"+path.ToString()+"','"+TextBox1.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
}
}
}
for showing the file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ShowImage.aspx.cs" Inherits="fetchImage.ShowImage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<table>
<tr>
<td>
<img src="<%#Eval("image_path") %>" height="100" width="100" />
<td><%#Eval("title") %></td>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
file show cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace fetchImage
{
public partial class ShowImage : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP- U0NOKBP\\SQLEXPRESS;Initial Catalog=Lnmi;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Images";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
DataList1.DataSource = dt;
DataList1.DataBind();
con.Close();
}
}
}
please create a table before proceeding
create table Images(image_path varchar(MAX), title varchar(50));
and lastly add a folder Images in your project by right clicking at your project name

ASP.NET Gridview Sorting not functioning

i m trying to implement a gridview on a web application, using asp.net. I m encountering a problem when it comes to sorting my datagrid, by a method - and i d like to ask for advice. This is my .aspx file:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Employee.aspx.cs" Inherits="GridViewDemo1.Employee" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView
ID="grvEmployee"
runat="server"
AutoGenerateColumns="true"
BackColor="AliceBlue"
ForeColor="Goldenrod"
BorderColor="YellowGreen"
BorderStyle="Groove"
Width="70%"
CellPadding="3"
CellSpacing="2"
AllowSorting="True"
OnSorting="GridView1_Sorting"
AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true" ViewStateMode="Enabled">
<RowStyle
HorizontalAlign="Center">
</RowStyle>
<FooterStyle
ForeColor="#8C4510"
BackColor="#F7DFB5">
</FooterStyle>
<PagerStyle
ForeColor="#8C4510"
HorizontalAlign="Center">
</PagerStyle>
<HeaderStyle
ForeColor="White"
Font-Bold="True"
BackColor="#A55129">
</HeaderStyle>
</asp:GridView>
</div>
</form>
and this is the .cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace GridViewDemo1
{
public partial class Employee : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
string selectSQL = "SELECT * from dbo.[User]";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Employee");
grvEmployee.DataSource = ds;
grvEmployee.DataBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//dataTable.DefaultView.Sort = e.SortExpression;
//grvEmployee.DataSource = dataTable;
grvEmployee.DataBind();
}
}
}
This is my web.config connectionstring:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=xxxxxx;Initial Catalog=yyyyyyy;User ID=zzzzz;Password=xxxxxx;" providerName="System.Data.SqlClient" />
The gridview gets populated properly, i used to get the "fired event Sorting which wasn't handled." but now i simply get no response from trying to sort a column. Does this even work with auto-generated columns? Where can i specify a sort expression? (Ascending/Descending etc)?
You have to do the initial DataBinding only if !IsPostback not on every consecutive postback:
if(!IsPostBack)
{
string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
string selectSQL = "SELECT * from dbo.[User]";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Employee");
grvEmployee.DataSource = ds;
grvEmployee.DataBind();
}
In GridView1_Sorting you have to select the ordered data from the database and assign it to the grid's DataSource property, then call grvEmployee.DataBind():
GridView Sorting Sample:https://stackoverflow.com/a/6602125/284240

Ajax cascading dropdownlist is not working for webservices methods

Need to bind drop down value from another drop down value, web methods not
firing even after added web reference, not showing any error.
I am getting error *method 500.
I am using visual studio and I have asp.net application as one project and a web service as another project.I am using web service in my asp.net application.
There is some sort of problem im my web service code. But i am unable to debug continuosly from asp.net application to web service.
I put break point both in application and web service but break point not activated in web service and it shows me connection error.
How can i do this while hosting on localhost?
my country.aspx code
<form id="form1" runat="server">
<ajax:ToolkitScriptManager EnablePageMethods="true" ID="tsmcascading" runat="server">
</ajax:ToolkitScriptManager>
<div>
<div>
<asp:DropDownList ID="ddlstate" runat="server" AutoPostBack="true">
</asp:DropDownList>
<ajax:CascadingDropDown ID="cddstate" runat="server" ServicePath="~/cascadingdropdown.asmx"
Category="stateid" ServiceMethod="addstate" TargetControlID="ddlstate" PromptText="select state"
LoadingText="Loading...">
</ajax:CascadingDropDown>
</div>
</div>
<div>
<div>
<asp:DropDownList ID="ddlcity" runat="server">
</asp:DropDownList>
<ajax:CascadingDropDown ID="CascadingDropDown1" runat="server" TargetControlID="ddlcity"
Category="stateid" ParentControlID="ddlstate" ServiceMethod="addcity" PromptText="select city"
ServicePath="~/cascadingdropdown.asmx" LoadingText="Loading...">
</ajax:CascadingDropDown>
</div>
</div>
</form>
my webservice code (.asmx)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using AjaxControlToolkit;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Specialized;
/// <summary>
/// Summary description for cascadingdropdown
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
// 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 cascadingdropdown : System.Web.Services.WebService
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["addcontact"].ToString());
public cascadingdropdown()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public CascadingDropDownNameValue[] addstate(string state, string city)
{
con.Open();
SqlCommand cmdstate = new SqlCommand("select stateid,statename from tblStates", con);
cmdstate.ExecuteNonQuery();
SqlDataAdapter dastate = new SqlDataAdapter(cmdstate);
DataSet dsstate = new DataSet();
dastate.Fill(dsstate);
con.Close();
List<CascadingDropDownNameValue> statesnames = new List<CascadingDropDownNameValue>();
foreach (DataRow dtrow in dsstate.Tables[0].Rows)
{
string stateid = dtrow["stateid"].ToString();
string statename = dtrow["statename"].ToString();
statesnames.Add(new CascadingDropDownNameValue(statename, stateid));
}
return statesnames.ToArray();
}
[WebMethod]
public CascadingDropDownNameValue[] addcity(string state, string city)
{
int stateid;
StringDictionary statedetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(state);
stateid = Convert.ToInt32(statedetails["state"]);
con.Open();
SqlCommand cmdcity = new SqlCommand("select cityid,stateid,cityname from tblcities where stateid=#stateid", con);
cmdcity.Parameters.AddWithValue("#stateid", stateid);
cmdcity.ExecuteNonQuery();
SqlDataAdapter dacity = new SqlDataAdapter(cmdcity);
DataSet dscity = new DataSet();
dacity.Fill(dscity);
con.Close();
List<CascadingDropDownNameValue> citynames = new List<CascadingDropDownNameValue>();
foreach (DataRow dtrow in dscity.Tables[0].Rows)
{
string cityid = dtrow["cityid"].ToString();
string cityname = dtrow["cityname"].ToString();
citynames.Add(new CascadingDropDownNameValue(cityid, cityname));
}
return citynames.ToArray();
}
}`
Try using the standard definition for functions used by AjaxControltoolkit cascading dropdown:
public CascadingDropDownNameValue[] addState(String knownCategoryValues, String category, String contextKey)
{
...
}
public CascadingDropDownNameValue[] addCity(String knownCategoryValues, String category, String contextKey)
{
...
}
Context key is not a mandatory parameter, you can ommit it if you do not need it.
I have totally the same problem, i found a "tutorial" and i tried to fit it with my own code, but i couldn't get it to work i was also getting method 500 errors.
Try use 100% of this websites code
http://www.aspdotnet-suresh.com/2011/01/introduction-here-i-will-explain-how-to.html
It worked for me, i just fitted some of the code at a time.

Autocomplete extender not firing

I have a ajax autocomplete extender and everything works fine. I mean sql procedure and others are fine but when I enter something to textbox nothing happened.
Why is that?
Here is my codes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Configuration;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
/// <summary>
/// Summary description for WebService
/// </summary>
[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]
public class WebService : System.Web.Services.WebService {
string[] arr;
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string[] testing(string prefixText)
{
if (prefixText.Length > 0)
{
string sql = "Select * From titles Where title like #title";
SqlDataAdapter da = new SqlDataAdapter(sql, "myconnectionstring is here");
da.SelectCommand.Parameters.Add("#title", 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["title"].ToString(), i);
i++;
}
return items;
}
arr[0] = "";
return arr;
}
}
Html side:
<%# Page Title="" Language="C#" MasterPageFile="~/adminpanel/adminpanel.master" AutoEventWireup="true" CodeFile="autocomplete.aspx.cs" Inherits="adminpanel_autocomplete" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
MinimumPrefixLength="1" ServiceMethod="testing" ServicePath="WebService.asmx" TargetControlID="TextBox1" Enabled="true">
</asp:AutoCompleteExtender>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
I wrote my jQuery AutoComplete handler.
So I fixed my question.
But still couldn't find the problem about ajax autocomplete extender.
Thanks.
You need to uncomment the following line from the webservice :
// [System.Web.Script.Services.ScriptService]

Resources