Textbox showing the default text - c#

I am facing a strange problem. Two of my textboxes in asp.net are showing the default text, but there is no default value is set not even in the .cs file.
Here is the the code for a textbox:
<tr>
<td>
<asp:TextBox ID="txtName" runat="server" ValidationGroup="reg" Height="32px" Width="155px"
Style="border: 1px solid #999; background-color: #eee; width: 250px; height: 25px"
type="text"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtName" Display="Dynamic"
ValidationGroup="reg" ErrorMessage="Please fill your name as your Id"></asp:RequiredFieldValidator>
</td>
</tr>
Code behind:
public partial class Registration : System.Web.UI.Page
{
MySqlConnection con = new MySqlConnection(WebConfigurationManager.ConnectionStrings["conn"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnRegister_Click(object sender, EventArgs e)
{
con.Open();
try
{
if (IsUsernameEmailExist())
{
Messagebox("Username/Email address already exists. Please try another");
return;
}
if (txtPassword.Text == txtConfirm.Text)
{
MySqlCommand cmd = new MySqlCommand("insert into MEMBERS (memberNAME,memberEMAIL,memberPASSWORD,memberPHONE,isACTIVE) values(#memberNAME,#memberEMAIL,#memberPASSWORD,#memberPHONE,#isACTIVE)", con);
cmd.Parameters.AddWithValue("#memberNAME", txtName.Text);
cmd.Parameters.AddWithValue("#memberEMAIL", txtEmail.Text);
cmd.Parameters.AddWithValue("#memberPASSWORD", txtPassword.Text);
cmd.Parameters.AddWithValue("#memberPHONE", txtPhone.Text);
cmd.Parameters.AddWithValue("#isACTIVE", Label1.Text);
cmd.ExecuteNonQuery();
Sendemail();
Clear();
Messagebox("User Register Successfully .Now check your mail verification link is sent to your mail. After verification you can access your account");
cmd.Dispose();
}
else
{
Messagebox("Passowrd Not Match");
}
}
catch
{
}
}
public void Sendemail()
{
string ActivationUrl;
try
{
MailMessage message = new MailMessage();
message.To.Add(txtEmail.Text);
message.Subject = "Verification Email";
ActivationUrl = Server.HtmlEncode("http://localhost:55655/WebSite2/Verification.aspx?memberID=" + GetUserID(txtEmail.Text));
message.Body = "<a href='" + ActivationUrl + "'>Click Here to verify your acount</a>";
message.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Credentials = new
smtp.EnableSsl = true;
smtp.Send(message);
}
catch
{
}
}
private string GetUserID(string Email)
{
MySqlCommand cmd = new MySqlCommand("SELECT memberID FROM MEMBERS WHERE memberEMAIL=#memberEMAIL", con);
cmd.Parameters.AddWithValue("#memberEMAIL", txtEmail.Text);
string memberID = cmd.ExecuteScalar().ToString();
return memberID;
}
private bool IsUsernameEmailExist()
{
MySqlCommand cmd = new MySqlCommand("Select * from MEMBERS where memberNAME='" + txtName.Text + "' or memberEMAIL='" + txtEmail.Text + "'", con);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
return true;
}
else
{
return false;
}
}
private void Messagebox(string Message)
{
Label lblMessageBox = new Label();
lblMessageBox.Text =
"<script language='javascript'>" + Environment.NewLine +
"window.alert('" + Message + "')</script>";
Page.Controls.Add(lblMessageBox);
}
public void Clear()
{
txtName.Text = "";
txtEmail.Text = "";
txtPassword.Text = "";
txtConfirm.Text = "";
txtPhone.Text = "";
}
}

Please add one of the following two combinations to your code
//do not change whole form tag, just add the autocomplete part
<form autocomplete="off">
//....
</form>
OR
add this to your elements directly
<asp:TextBox id="yourid" runat="server" autocomplete="off">
</asp:TextBox>

I think it might just be good practice to call the Clear() method in your Page_Load() if (!Page.isPostBack) and might solve your problem?

if (window.getSelection)
window.getSelection().removeAllRanges();
else if (document.selection)
document.selection.empty();

Related

Radio button returns wrong answer if no selection was submitted

I am using the below code for my online quiz using ASP.NET and SQL Server 2008. I need my radio button to return wrong answer if nothing checked after pressing submit.
<div id="questionsdiv" runat="server" >
<asp:Label ID="lblalert" runat="server" ForeColor="Red" Font-Size="20px" Visible="false" /><br />
<asp:Repeater ID="questionsrpt" runat="server" OnItemDataBound="questionsrpt_ItemDataBound" >
<ItemTemplate>
<asp:HiddenField ID="hfID" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "id")%>' Visible="false" />
<asp:RequiredFieldValidator ID="rfvquiz" runat="server" Display="Dynamic" ControlToValidate="rbloptions" ValidationGroup="quizvalidation" ForeColor="Red" Text="*" SetFocusOnError="true"/> <asp:Label ID="lblquestion" runat="server" Font-Size="20px" Text='<%# DataBinder.Eval(Container.DataItem, "title")%>' /><br />
<asp:RadioButtonList ID="rbloptions" runat="server" ValidationGroup="quizvalidation" Font-Size="14px" style="font-weight:bold"/>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="btnsubmit" runat="server" OnClick="btnsubmit_Click" Text="Submit" ValidationGroup="quizvalidation" />
</div>
code behind
//quiz answers submitted
protected void btnsubmit_Click(object sender, EventArgs e)
{
SqlDataReader dReader;
string email = "";
string name = "";
string selectedanswer = "";
string correctanswer = "";
int questionId = 0;
int questionscount = 0;
int correctcount = 0;
int wrongcount = 0;
int success = 0;
ArrayList answersList = new ArrayList();
Page.Validate();
if (Page.IsValid)
{
email = txtemail.Text.Trim();
name = txtname.Text.Trim();
//check if this account has already taken the quiz.
DataTable accounts = new DataTable();
SqlCommand checkentrycmd = new SqlCommand("select * from " + quizresponsestable + " where quizid=#quizid and email=#email");
checkentrycmd.Parameters.AddWithValue("quizid", quizId);
checkentrycmd.Parameters.AddWithValue("email", email);
db checkentry = new db();
accounts = checkentry.returnDataTable(checkentrycmd);
if (accounts.Rows.Count > 0)
{
quizdetails.Visible = false;
detailsdiv.Visible = false;
questionsdiv.Visible = false;
lblmessage.Visible = true;
lblmessage.Text = "You have already taken this quiz!";
}
else
{
foreach (RepeaterItem item in questionsrpt.Items)
{
// Checking the item is a data item
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
//get the questionid
var hfId = item.FindControl("hfID") as HiddenField;
questionId = Convert.ToInt32(hfId.Value);
//get the submitted answer
var rdbList = item.FindControl("rbloptions") as RadioButtonList;
selectedanswer = rdbList.SelectedValue;
//disable to prevent submitting again
rdbList.Enabled = false;
//get the correct answer
SqlCommand getanswercmd = new SqlCommand("select optionid from " + quizquestionanswertable + " where questionid=#questionid");
getanswercmd.Parameters.AddWithValue("questionid", questionId);
db getanswer = new db();
dReader = getanswer.returnDataReader(getanswercmd);
if (!dReader.HasRows)
{
//can't find this question/answer
}
else
{
while (dReader.Read())
{
correctanswer = dReader["optionid"].ToString();
}
}
//compare both answers
if (selectedanswer == correctanswer)
{
correctcount++;
rdbList.SelectedItem.Attributes.Add("style", "color: #006400");
}
else
{
wrongcount++;
rdbList.SelectedItem.Attributes.Add("style", "color: #ff0000");
rdbList.Items.FindByValue(correctanswer).Attributes.Add("style", "color: #006400");
}
//add the submitted answer to list
answersList.Add(new string[] { questionId.ToString(), selectedanswer });
}
}
//create entry
SqlCommand insertentrycmd = new SqlCommand("insert into " + quizresponsestable + " (quizid, email, name, correctanswers, wronganswers, lastupdated) values (#quizid, #email, #name, #correctanswers, #wronganswers, #lastupdated);SELECT CAST(scope_identity() AS int)");
insertentrycmd.Parameters.AddWithValue("quizid", quizId);
insertentrycmd.Parameters.AddWithValue("email", email);
insertentrycmd.Parameters.AddWithValue("name", name);
insertentrycmd.Parameters.AddWithValue("correctanswers", correctcount);
insertentrycmd.Parameters.AddWithValue("wronganswers", wrongcount);
insertentrycmd.Parameters.AddWithValue("lastupdated", updatedate);
db insertentry = new db();
success = insertentry.ReturnIDonExecuteQuery(insertentrycmd);
//display the result on screen
if (success > 0)
{
foreach (string[] arr in answersList)
{
SqlCommand insertresponsecmd = new SqlCommand("insert into " + quizuserreponsetable + " (responseid, questionid, optionid, lastupdated) values (#responseid, #questionid, #optionid, #lastupdated)");
insertresponsecmd.Parameters.Clear();
insertresponsecmd.Parameters.AddWithValue("responseid", success);
insertresponsecmd.Parameters.AddWithValue("questionid", arr[0].ToString());
insertresponsecmd.Parameters.AddWithValue("optionid", arr[1].ToString());
insertresponsecmd.Parameters.AddWithValue("lastupdated", updatedate);
db insertresponses = new db();
insertresponses.ExecuteQuery(insertresponsecmd);
}
detailsdiv.Visible = false;
questionscount = correctcount + wrongcount;
lblalert.Visible = true;
//get the completion description from database table
SqlDataReader Treader;
SqlCommand getcompletiondesc = new SqlCommand("select completiondescription from " + quizdetailstable + " where id=#quizid");
getcompletiondesc.Parameters.AddWithValue("quizid", quizId);
db getdesc = new db();
Treader = getdesc.returnDataReader(getcompletiondesc);
if (!Treader.HasRows)
{
lblalert.Text = "Thanks for taking the Quiz." + "<br />" + "You have answered <span style='color:#006400;'>" + correctcount + "</span> questions correctly out of " + questionscount + "<br />";
}
else
{
while (Treader.Read())
{
string completiondesc = Treader["completiondescription"].ToString();
lblalert.Text = completiondesc + "<br />" + "You have answered <span style='color:#006400;'>" + correctcount + "</span> questions correctly out of " + questionscount + "<br />";
}
}
btnsubmit.Visible = false;
}
else
{
lblalert.Visible = true;
lblalert.Text = "Sorry! we could not process your request. Please try again.";
}
}
}
else
{
lblalert.Visible = true;
lblalert.Text = "Please answer all the questions!";
}
}
A question that I have is this:
If you are starting with an empty string for the SelectedValue, why don't you check the ensure that string.IsNullOrEmpty() fails for the value in question? The Page.IsValid() method will return "true" because, as far as it is concerned, the information that it uses to determine whether the Page is validated is complete.
And this part is free: (IMHO) if you are going to use a ValidationGroup, use a ValidationSummary as well. That way, you don't have to worry about individual labels

Link Button with query string in ASP.NET

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;
}
}

How can I display image in gridview with 3 tier architecture?

For data access layer:
Source:
public string insert_details(bisuness_object user_details)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("insert into tbl_rgsthome values(#firstname,#lastname,#emailid,#password,#address,#upload)", con);
try
{
cmd.Parameters.AddWithValue("#firstname", user_details.firstname_value);
cmd.Parameters.AddWithValue("#lastname", user_details.lastname_value);
cmd.Parameters.AddWithValue("#emailid", user_details.emailid_value);
cmd.Parameters.AddWithValue("#password", user_details.pass_value);
cmd.Parameters.AddWithValue("#address", user_details.addr_value);
cmd.Parameters.AddWithValue("#upload", user_details.fileupl_value);
//cmd.Parameters.AddWithValue("#imagepath", user_details.imgpth_value);
return cmd.ExecuteNonQuery().ToString();
}
catch (Exception show_error)
{
throw show_error;
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
}
home.aspx:
public string getimage(object ob)
{
string img = #"/image/" + ob.ToString();
return img;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{
byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Image = FileUpload1.PostedFile;
Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);
bisuness_object bo = new bisuness_object();
// cmd.Parameters.AddWithValue("#imagepath", ("#uploadimage") + filename);
bo.firstname_value = TextBox1.Text;
bo.lastname_value = TextBox2.Text;
bo.emailid_value = TextBox3.Text;
bo.pass_value = TextBox4.Text;
bo.addr_value = TextBox6.Text;
bo.fileupl_value = FileUpload1.FileName.ToString();
bisuness_layer bl = new bisuness_layer();
bind();
try
{
string result = bl.record_insert(bo);
}
catch (Exception info)
{
throw info;
}
finally
{
bo = null;
bl = null;
bind();
}
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
TextBox6.Text = "";
}
}
how to solve it.....please help me
i want to image in gridview
bind the image tag inside the gridview dynamically
by giving the path dynamically
<asp:Image ID="image" Style="width:100px; height:100px;" runat="server" ImageUrl='<%# "~/folder/subfolder/" + Eval("id") +"."+ Eval("imagetype") %>' />
and the method for binding the gridview
protected void GetDayoffer()
{
gridview1.DataSource = bl.method();
gridview1.DataBind();
}
hope this will help you or recovert the bytes into image again and bind it into gridview

Getting updated value of Textbox in asp.net and c#

I am searching and posting a lot in this issue,but could not get the satisfactory answer.I wanted to make sure that whenever I am making a call to server the value of Textbox should be the one which is the most updated one.
But when I am making the call to server the old value of the textbox persists.I know it is something to do with the postback,but I am not getting the exact way to get the updated value of textbox in my .cs file.
Please tell me what are the necessary steps that I should take to always get the latest value of the textbox.
Here is my code which is not working:
protected void Page_Load(object sender, EventArgs e)
{
int contentID = Convert.ToInt32(Request.QueryString["contentid"]);
if (contentID != 0)
{
if (!this.IsPostBack)
{
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text="Inside not PostBack";
}
else
{
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text="Inside PostBack";
}
}
else
Response.Write("Invalid URL for article");
}
public void getContentBody(int contentID)
{
try
{
//////////////Opening the connection///////////////
mycon.Open();
string str = "select content from content where contentID='" + contentID + "'";
//Response.Write(str);
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = str;
dr = command1.ExecuteReader();
if (dr.Read())
{
content = dr[0].ToString();
}
}
catch (Exception ex)
{
Response.Write("Exception reading data" + ex);
}
finally
{
dr.Close();
mycon.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
//string textboxvalue = Request.Form[TextBox1.UniqueID];
mycon.Open();
string query = "update content set content='" +TextBox1.Text + "' where contentID= '"+contentID +"'";
msg_lbl.Text = query;
try
{
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = query;
command1.ExecuteNonQuery();
msg_lbl.Text = "text" + TextBox1.Text;
}
catch (Exception ex)
{
msg_lbl.Text = "Exception in saving data" + ex;
}
finally
{
mycon.Close();
}
}
Here is my aspx page code:
<asp:TextBox ID="TextBox1" runat="server" Height="500px"
TextMode="MultiLine" Width="90%" AutoPostBack="True"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="Delete post" />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Save changes" />
<asp:Button ID="Button3" runat="server" Text="Cancel" />
</p>
Please also tell me the reason why it is not working and how I can make it work.
Thanks,
Amandeep
According to the ASP.NET's life cycle, Page_Load executes before Button2_Click, so you have to show your updated text in the Button2_Click:
protected void Page_Load(object sender, EventArgs e)
{
contentID = Convert.ToInt32(Request.QueryString["contentid"]);
if (contentID != 0)
{
if (!this.IsPostBack)
{
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text = "Inside not PostBack";
}
}
else
Response.Write("Invalid URL for article");
}
public void getContentBody(int contentID)
{
try
{
//////////////Opening the connection///////////////
mycon.Open();
string str = "select content from content where contentID='" + contentID + "'";
//Response.Write(str);
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = str;
dr = command1.ExecuteReader();
if (dr.Read())
{
content = dr[0].ToString();
}
}
catch (Exception ex)
{
Response.Write("Exception reading data" + ex);
}
finally
{
dr.Close();
mycon.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
//string textboxvalue = Request.Form[TextBox1.UniqueID];
mycon.Open();
string query = "update content set content='" + TextBox1.Text + "' where contentID= '" + contentID + "'";
msg_lbl.Text = query;
try
{
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = query;
command1.ExecuteNonQuery();
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text = "text" + TextBox1.Text;
}
catch (Exception ex)
{
msg_lbl.Text = "Exception in saving data" + ex;
}
finally
{
mycon.Close();
}
}

AutoCompleteExtender AJAX Question

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;
}

Categories

Resources