AjaxControlToolkit AutoCompleteExtender is not displaying suggestions - asp.net

I am using AutoCompleteExtender in asp.net to fetch name and designation based on token(empno).
The is pulled from database and I could see it in the network tab of Chrome Dev-tools. But it is not rendered as suggestion list.
My attempt for the code:
<div class="modal-body">
<div class="form-group">
<label for="pToken">Token</label>
<asp:TextBox ID="pToken" runat="server" CssClass="form-control" placeholder="Enter Token No" />
<ajaxcontrol:AutoCompleteExtender runat="server"
ID="acToken" TargetControlID="pToken" MinimumPrefixLength="3"
EnableCaching="true" FirstRowSelected="false"
ServiceMethod="getPatients" ServicePath="CheckPatientDetails.aspx"
CompletionSetCount="6" DelimiterCharacters="|"
CompletionListItemCssClass="AutoCompleteExtender_CompletionListItem"
CompletionListHighlightedItemCssClass="AutoCompleteExtender_HighlightedItem"
CompletionListCssClass="AutoCompleteExtender_CompletionList">
</ajaxcontrol:AutoCompleteExtender>
</div>
<div class="form-group">
<label for="pName">Name</label>
<asp:TextBox ID="pName" runat="server" CssClass="form-control" placeholder="Enter patient name" required />
</div>
<div class="form-group">
<label for="pDesig">Designation</label>
<asp:TextBox ID="pDesig" runat="server" CssClass="form-control" placeholder="Enter designation" />
</div>
<div class="form-group">
<label for="pType">Type</label>
<asp:DropDownList ID="pType" runat="server" CssClass="form-control" required>
<asp:ListItem Value="E" Selected="True">Employee</asp:ListItem>
<asp:ListItem Value="I">In Patient</asp:ListItem>
<asp:ListItem Value="O">Out Patient</asp:ListItem>
<asp:ListItem Value="X">Others</asp:ListItem>
</asp:DropDownList>
</div>
The backend code for the same is below :
[WebMethod]
[System.Web.Script.Services.ScriptMethod()]
public static List<Patient> getPatients(string prefixText, int count)
{
List<Patient> patientList = new List<Patient>();
OracleConnection con = null;
OracleDataReader odr = null;
string query = "select nvl(emp.empid,'') token,DECODE(SHORTNAME,NULL,FIRSTNAME,SHORTNAME) name,DESIGSHORT desigdesc" +
" from employee emp join designation desig on (emp.desigcode = desig.desigcode and desig.isactive = 'Y') " +
" where empid like '%" + prefixText + "%' and emp.EMPSTATUS = 'A' order by empid";
try
{
con = getHRMSConnection();
con.Open();
using (con)
{
using (OracleCommand cmd = new OracleCommand(query, con))
{
odr = cmd.ExecuteReader();
Patient patient = null;
while (odr.Read())
{
patient = new Patient();
patient.setToken(Convert.ToString(odr["token"]));
patient.setName(Convert.ToString(odr["name"]));
patient.setDesignation(Convert.ToString(odr["desigdesc"]));
patientList.Add(patient);
}
}
}
}
catch (Exception ex)
{
}
return patientList;
}

There are many reasons for the issue you are facing. Starting with basic check if service path is correct or not.
Secondly, have you declared with [webmethod] above your function fetching data.

The task is done now, I am getting the autocomplete rendered properly. Posting for those who may refer to this later on.
I used this link to get the autocomplete rendered on modal.
Autocomplete extender not working inside modal popup extender
Now my modal body is
<div class="modal-body">
<div class="form-group">
<asp:AutoCompleteExtender ServiceMethod="GetSearch" MinimumPrefixLength="2" CompletionInterval="10"
EnableCaching="false" CompletionSetCount="10" TargetControlID="pToken" ID="AutoCompleteExtender2"
runat="server" FirstRowSelected="false" CompletionListCssClass="autocomplete_completionListElement" CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem">
</asp:AutoCompleteExtender>
<label for="pToken">Token</label>
<asp:TextBox ID="pToken" runat="server" CssClass="form-control" placeholder="Enter Token No"/>
</div>
<div class="form-group">
<label for="pName">Name</label>
<asp:TextBox ID="pName" runat="server" CssClass="form-control" placeholder="Enter patient name" required />
</div>
<div class="form-group">
<label for="pDesig">Designation</label>
<asp:TextBox ID="pDesig" runat="server" CssClass="form-control" placeholder="Enter designation" />
</div>
<div class="form-group">
<label for="pType">Type</label>
<asp:DropDownList ID="pType" runat="server" CssClass="form-control" required>
<asp:ListItem Value="E" Selected="True">Employee</asp:ListItem>
<asp:ListItem Value="I">In Patient</asp:ListItem>
<asp:ListItem Value="O">Out Patient</asp:ListItem>
<asp:ListItem Value="X">Others</asp:ListItem>
</asp:DropDownList>
</div>
</div>
And server side code is :
[WebMethod]
[System.Web.Script.Services.ScriptMethod()]
public static List<string> GetSearch(string prefixText, int count)
{
OracleConnection con = null;
OracleDataAdapter oda = null;
DataTable dt;
prefixText = prefixText.ToLower();
DataTable Result = new DataTable();
List<string> Output = new List<string>();
string str = "select nvl(emp.empid,'') ||'('||DECODE(SHORTNAME,NULL,FIRSTNAME,SHORTNAME)||','|| DESIGSHORT ||')' employee" +
" from employee emp join designation desig on (emp.desigcode = desig.desigcode and desig.isactive = 'Y') " +
" where lower(empid) like '%" + prefixText + "%' and emp.EMPSTATUS = 'A' order by empid";
con = getHRMSConnection();
using (con)
{
try
{
con.Open();
oda = new OracleDataAdapter(str, con);
dt = new DataTable();
oda.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
Output.Add(dt.Rows[i][0].ToString());
}
}
catch (Exception ex)
{
}
}
return Output;
}

Related

how to store data into database using text-area

How to store data in the database.
it will show the following exception
Additional information: Procedure or function 'spUploadImage' expects parameter '#detail', which was not supplied.
Following is the Movies.aspx file contents :
<html>
<head>
<script>
var maxAmount = 250;
function textCounter(textField, showCountField) {
if (textField.value.length > maxAmount) {
textField.value = textField.value.substring(0, maxAmount);
} else {
showCountField.value = maxAmount - textField.value.length;
}
}
</script>
</head>
<body>
<center>
<asp:Label ID="label3" Text="Name of Movie: " runat="server"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br /><br />
<asp:Label ID="label4" Text="Details of Movie: " runat="server"></asp:Label><br />
<textarea id="txtCommentBox" name="txtCommentBox" rows="6" style="width:340px;" onKeyDown="textCounter(this.form.txtCommentBox,this.form.countDisplay);" onKeyUp="textCounter(this.form.txtCommentBox,this.form.countDisplay);"></textarea>
<br />
<input readonly type="text" name="countDisplay" size="3" maxlength="3" value="250"> Characters Remaining
<br />
<br />
<asp:Label ID="label2" Text="Select Image of Movie: " runat="server"></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:HyperLink ID="HyperLink1" runat="server">View Uploaded Image</asp:HyperLink>
</center>
</body>
</html>
</asp:Content>
Following is the Movies.aspx.cs file contents :
public partial class Movies : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Label1.Visible = false;
HyperLink1.Visible = false;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string txt = TextBox1.Text;
string text = Request.Form["txtCommentBox_1"];
HttpPostedFile postedFile= FileUpload1.PostedFile;
string fileName = Path.GetFileName(postedFile.FileName);
string fileExtension = Path.GetExtension(fileName);
int fileSize = postedFile.ContentLength;
if(fileExtension.ToLower()==".jpg" || fileExtension.ToLower()==".png" || fileExtension.ToLower()==".bmp" || fileExtension.ToLower()==".gif")
{
Stream stream= postedFile.InputStream;
BinaryReader binaryReader = new BinaryReader(stream);
byte[] bytes = binaryReader.ReadBytes((int)stream.Length);
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con=new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spUploadImage",con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramName = new SqlParameter()
{
ParameterName = "#Name",
Value = fileName
};
cmd.Parameters.Add(paramName);
SqlParameter paramSize = new SqlParameter()
{
ParameterName = "#Size",
Value = fileSize
};
cmd.Parameters.Add(paramSize);
SqlParameter parammName = new SqlParameter()
{
ParameterName = "#mName",
Value = txt
};
cmd.Parameters.Add(parammName);
SqlParameter paramImageData = new SqlParameter()
{
ParameterName = "#ImageData",
Value = bytes
};
cmd.Parameters.Add(paramImageData);
SqlParameter paramdetail = new SqlParameter()
{
ParameterName = "#detail",
Value = text
};
cmd.Parameters.Add(paramdetail);
SqlParameter paramNewId = new SqlParameter()
{
ParameterName = "#NewId",
Value = -1,
Direction=ParameterDirection.Output
};
cmd.Parameters.Add(paramNewId);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Visible = true;
Label1.Text = "Upload Successful";
Label1.ForeColor = System.Drawing.Color.Green;
HyperLink1.Visible = true;
HyperLink1.NavigateUrl = "~/Moviesimg.aspx?Id="+cmd.Parameters["#NewId"].Value.ToString();
}
}
else
{
Label1.Visible = true;
Label1.Text = "Only Images (.jpg, .png, .gif and .bmp) can be uploaded...";
Label1.ForeColor = System.Drawing.Color.Red;
HyperLink1.Visible = false;
}
}
}
and the stored procedure is as follows :
create proc spUploadImage
#Name nvarchar(255),
#Size int,
#ImageData varbinary(max),
#mName nvarchar(50),
#detail nvarchar(300),
#NewId int output
as
Begin
Insert into tblImages
values(#Name,#Size,#mName,#detail,#ImageData)
select #NewId = SCOPE_IDENTITY()
End
But I want to get a text from the text area and to store in the database.
but it raises an exception...
You are missing a form tag. Use an ASP control instead of a plain HTML control - all the other controls are ASP so be consistent.
<html>
<body>
<form id="form1" runat="server">
<asp:TextBox id="txtImagename1" TextMode="multiline" Columns="50"
Rows="1" runat="server" />
</form>
</body>
</html>
protected void Button1_Click(object sender, EventArgs e)
{
string text = Server.HtmlEncode(txtImagename1.Text);
...
}
The Request.Form collection cannot be used if your form is over 100 KB:
msdn.microsoft.com/en-us/library/ms525985(v=vs.90).aspx
If you are setting runat="server" to any control, in that case the control must be placed inside a form tag with runat="server" like following
<html>
<body>
<form id="form1" runat="server">
<center>
<textarea id="txtImagename1" name="txtImagename1" runat="server" rows="1" cols="50">
</textarea>
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:HyperLink ID="HyperLink1" runat="server">View Uploaded Image</asp:HyperLink>
</center>
</form>
</body>
</html>
To access this on server side you can simply use the the InnerText property of the TextArea as following.
txtImagename1.InnerText
If you want you can also access it using Form object also as following.
Request.Form["txtImagename1"]
For this the control can be simple TextArea without runat attribute.

DropDownList SelectIndexChanged not working?

This seems to be a common problem. I have tried different solutions but its still not working. This is my code.
HTML:
<div class="form-group">
<label for="exampleInputEmail1">Artist *</label>
<asp:DropDownList ID="artistDropdown" runat="server" CssClass="form-control" AutoPostBack="True" OnSelectedIndexChanged="artistDropdown_SelectedIndexChanged" ViewStateMode="Enabled"></asp:DropDownList>
<asp:TextBox ID="mytest" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="artistDropdown" SetFocusOnError="true" ErrorMessage="Required Field" Font-Bold="True" Font-Names="Arial" Font-Size="X-Small" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:Label ID="lblMessage" runat="server" CssClass="help-block" Visible="False">Cant select Artist with no Manager</asp:Label>
</div>
Function: OnSelectedIndexChanged
protected void artistDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedArtist = artistDropdown.SelectedValue;
mytest.Text = selectedArtist;
string query = "Select [Manager ID] from Artist Where ID = '" + selectedArtist + "'";
string myConnection = dbController.connectionString;
SqlConnection conn = new SqlConnection(myConnection);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
object obj = cmd.ExecuteScalar();
if (obj is System.DBNull)
{
artistDropdown.SelectedValue = "";
lblMessage.Visible = true;
}
else
{
lblMessage.Visible = false;
}
conn.Close();
}
I am loading DropDownList in Page_Load() function and AutoPostBack="True" is set for DropDownList.
I have also made a TextBox which is being set to the selectedValue from DropDownList to check if on OnSelectedIndexChanged is firing. But text box remains empty.
What am I doing wrong?
Did you put the binding of your dropdown in the if (!postback) {} ?
If you rebind the list after every postback, you get the value of the first list item when you reach the artistDropdown_SelectedIndexChanged event.
If this item has an empty string value...

Contact form send even if the field(s) are empty

Please help...
I just got the below code from the internet and don't know how to fix the issue.
Issue is:- even if the form is empty or one of the fields is empty, I still receive the email.
I think I need to add some validation here but I don't know how. I am not a programmer and new to asp.
Here is the code.
the ASPX is:
<%# Page Language="C#" AutoEventWireup="true" ValidateRequest = "false" CodeFile="contact.aspx.cs" Inherits="_Default" %>
<html>
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<div class="inp_title"><asp:Label ID="Label1" runat="server" Text="Name*" /></div>
<div>
<asp:TextBox ID="txtName" runat="server" ValidationGroup = "contact" CssClass="inp_h" /><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter your name." ControlToValidate = "txtName" Display="Dynamic" /></div>
<div class="inp_title"><asp:Label ID="Label2" runat="server" Text="Subject*" /></div>
<div>
<asp:TextBox ID="txtSubject" runat="server" /><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*" ControlToValidate = "txtSubject" Display="Dynamic" /></div>
<div class="inp_title"><asp:Label ID="Label3" runat="server" Text="Email Address*" /></div>
<div>
<asp:TextBox ID="txtEmail" runat="server" CssClass="inp_h" Display="Dynamic" /><br />
<asp:RegularExpressionValidator id="valRegEx" runat="server" ControlToValidate="txtEmail" ValidationExpression=".*#.*\..*" ErrorMessage="Please enter a valid email address." Display="Dynamic" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Please enter your email address." ControlToValidate = "txtEmail" />
</div>
<div class="inp_title-2"><asp:Label ID="Label4" runat="server" Text="Message*" /></div>
<div>
<asp:TextBox ID="txtBody" runat="server" TextMode = "MultiLine" CssClass="inp_h" Display="Dynamic" /><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Please enter your message." ControlToValidate = "txtBody" />
</div>
<div class="inp_h"><asp:FileUpload ID="FileUpload1" runat="server" /></div>
<asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" CssClass="form-buttons"/>
<asp:Label ID="lblMessage" runat="server" Text="" ForeColor = "Green" />
</form>
</body>
</html>
The code-behind is :
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Net.Mail;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSend_Click(object sender, EventArgs e)
{
MailMessage mm = new MailMessage("email1#domain.com", "email2#domain.com");
mm.Subject = txtSubject.Text;
mm.Body = "Name: " + txtName.Text + "<br /><br />Email: " + txtEmail.Text + "<br /><br />Message:<br />" + txtBody.Text;
if (FileUpload1.HasFile)
{
string FileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName) ;
mm.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileName));
}
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.office365.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "email1#domain.com";
NetworkCred.Password = "emai1password";
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
lblMessage.Text = "Email Sent Sucessfully.";
}
}
Here you go, this will not send the email if the fields have not been filled out if you're not using validation - otherwise just add 'causesvalidation=true' to your submit button as per the earlier answer
protected void btnSend_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(txtName.Text) && !string.IsNullOrWhiteSpace(txtEmail.Text) && !string.IsNullOrWhiteSpace(txtBody.Text) )
{
MailMessage mm = new MailMessage("email1#domain.com", "email2#domain.com");
mm.Subject = txtSubject.Text;
mm.Body = "Name: " + txtName.Text + "<br /><br />Email: " + txtEmail.Text + "<br /><br />Message:<br />" + txtBody.Text;
if (FileUpload1.HasFile)
{
string FileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName) ;
mm.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileName));
}
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.office365.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "email1#domain.com";
NetworkCred.Password = "emai1password";
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
lblMessage.Text = "Email Sent Sucessfully.";
}
else
{
lblMessage.Text = "You need to fill in the fields.";
}
}
your problem is here :
<asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" CssClass="form-buttons"/>
use this instead : CausesValidation="true" in your button. This will validate your required field before post event is fired.
<asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" CssClass="form-buttons" CausesValidation="true"/>
You need to have a required field validator for the textbox
just use
CausesValidation="true"
inside your button control, this will validate your controls client side.
Like I said :
<asp:Button ... CausesValidation="true"/>
or you can validate it at server side too.

ASP.Net dropdown always return first value on button click event

I am trying to save value from a simple asp.net form.
I have few controls on the page like drop-down & text-box's
I fill the first drop-down on page load with Language & trigger post-bask on same to fill the second drop-down ddCategoryType which it fills with correct values based on the language selected, but problem is when i try to get the value on button click event value for ddCategoryType.SelectedItem.Value always return 0 for some reason which i am not able figure out right now
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddSelectLanguage.Items.Clear();
ddSelectLanguage.DataSource = DataProvider.GetLanguages();
ddSelectLanguage.DataBind();
ddSelectLanguage.Items.Insert(0, new ListItem("Select Language", "0"));
}
else
{
ddCategoryType.Items.Clear();
String strSql = "SELECT TypeName, TypeID FROM CategoryType WHERE LangID =" + ddSelectLanguage.SelectedItem.Value.ToString();
DataSet ds = new DataSet();
ds = DataProvider.Connect_Select(strSql);
ddCategoryType.DataSource = ds;
ddCategoryType.DataBind();
ddCategoryType.Items.Insert(0, new ListItem("Select Type", "0"));
}
}
protected void btnSaveCategory_Click(object sender, EventArgs e)
{
objArtCat.LanguageID = int.Parse(ddSelectLanguage.SelectedItem.Value.ToString());
objArtCat.CategoryName = txtCategoryName.Text;
objArtCat.CategoryType = int.Parse(ddCategoryType.SelectedItem.Value.ToString());
objArtCat.CategoryActive = bool.Parse(ddCategoryActive.SelectedItem.Value.ToString());
try
{
//bool result;
//result = objBLAddArticleCategory.CreateNewArticleCategory(objArtCat);
//if (result == true)
//{
// Response.Redirect("PageMessage.aspx?msg='Category has been Create Successfully'", true);
//}
//else
//{
//}
}
catch (Exception)
{ }
}
SAMPLE .ASPX CODE
<div class="row"></div>
<div class="row">
<asp:Label ID="lblSelectLang" CssClass="txtLabel" Text="Select Language :" runat="server" ></asp:Label>
<asp:DropDownList ID="ddSelectLanguage" runat="server" CssClass="ddGeneral"
DataTextField="LangName" DataValueField="LangID" CausesValidation="True"
AutoPostBack="True" >
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvddLanguage" runat="server" ErrorMessage="Please Select Language" ControlToValidate="ddSelectLanguage"
InitialValue="Select Language" ValidationGroup="atpAddNewArticle" ></asp:RequiredFieldValidator>
</div>
<div class="row">
<asp:Label ID="lblCategoryName" CssClass="txtLabel" runat="server" Text="Category Name :"></asp:Label>
<asp:TextBox ID="txtCategoryName" runat="server" CssClass="txtbox300"></asp:TextBox>
<asp:RequiredFieldValidator ID="RFVtxtAuthorName" runat="server" ErrorMessage="*"
ControlToValidate="txtCategoryName" ValidationGroup="atpAddNewArticle" CssClass="validation"></asp:RequiredFieldValidator>
</div>
<div class="row">
<asp:Label ID="lblCategoryType" CssClass="txtLabel" runat="server" Text="Category Type :"></asp:Label>
<asp:DropDownList ID="ddCategoryType" runat="server" CssClass="ddGeneral" DataTextField="TypeName" DataValueField="TypeID" >
</asp:DropDownList>
</div>
<div class="row">
<asp:Label ID="lblCategoryActive" CssClass="txtLabel" runat="server" Text="Category Active :"></asp:Label>
<asp:DropDownList ID="ddCategoryActive" runat="server" CssClass="ddGeneral" >
<asp:ListItem Value="False" Selected="True">NO</asp:ListItem>
<asp:ListItem Value="True">YES</asp:ListItem>
</asp:DropDownList>
</div>
<div class="rowButton">
</br>
<asp:Button ID="btnUpdateArticle" runat="server" Text="Save Category" CssClass="btn" ValidationGroup="atpAddNewArticle" onclick="btnSaveCategory_Click" /> <input id="Reset" type="reset" class="btn" value="Reset" />
</div>
OutPut for ddCategoryType after postback
<div class="row">
<span class="txtLabel" id="MainContent_lblCategoryType">Category Type :</span>
<select class="ddGeneral" id="MainContent_ddCategoryType" name="ctl00$MainContent$ddCategoryType">
<option value="0" selected="selected">Select Type</option>
<option value="1">Article</option>
<option value="2">News</option>
<option value="3">Sports</option>
<option value="4">People</option>
<option value="5">Message</option>
</select>
</div>
In your Page_Load you are clearing the contents of ddCategoryType and therefore the SelectedIndex is reset to 0.
Remember that the Page_Load is always called, and it happens BEFORE the Button_Click event.
There are a few ways to handle this, for instance: don't perform all the code in your Page_Load's else clause if the SelectedIndex >= 0
Since you want to populate ddCategoryType based on a selected value from ddSelectLanguage, then populate the DDL based on that interaction, not in the Page_Load.
protected void Page_Load(object sender, EventArgs e)
{
ddSelectLanguage.SelectedIndexChanged += new
EventHandler(ddSelectLanguage_SelectedIndexChanged);
if (!IsPostBack)
{
ddSelectLanguage.Items.Clear();
ddSelectLanguage.DataSource = DataProvider.GetLanguages();
ddSelectLanguage.DataBind();
ddSelectLanguage.Items.Insert(0, new ListItem("Select Language", "0"));
}
}
Then
void ddSelectLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
ddCategoryType.Items.Clear();
String strSql = "SELECT TypeName, TypeID FROM CategoryType WHERE LangID =" + ddSelectLanguage.SelectedItem.Value.ToString();
DataSet ds = new DataSet();
ds = DataProvider.Connect_Select(strSql);
ddCategoryType.DataSource = ds;
ddCategoryType.DataBind();
ddCategoryType.Items.Insert(0, new ListItem("Select Type", "0"));
}
also, make your query take parameters.

Text not getting inserted into table, but only auto incrementing other column

I have multiple textboxes that goes into a table called dbo.skills
dbo.Skills SkillID (PK- AutoIncrement) | SkillName
So when I used this method, the name is not getting stored but only SkillID is getting auto-incremented. Here is my .cs code
public void InsertSkillInfo()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
try
{
for (int i = 1; i <= 4; i++)
{
conn.Open();
//string skill = (TextBox)((Page.FindControl("TextBox" + i.ToString()))).Text;
var skill = "";
var control = Page.FindControl("TextBox" + i.ToString()) as TextBox;
if (control != null)
{
skill = control.Text;
}
const string sqlStatement = "INSERT INTO Skills (SkillName) VALUES (#SkillName)";
SqlCommand cmd = new SqlCommand(sqlStatement, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#SkillName", skill);
cmd.ExecuteNonQuery();
conn.Close();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
After entering values in textboxes, table looks like this-
Dbo.Skills
SkillID | SkillName
1 |
2 |
3 |
4 |
ASPX code:
<asp:Label ID="Label1" class="caption" runat="server" Text="Skill Name"></asp:Label>
<asp:TextBox ID="TextBox1" class="box" runat="server"></asp:TextBox> <br /> <br />
<asp:Label ID="Label2" class="caption" runat="server" Text="Skill Name"></asp:Label>
<asp:TextBox ID="TextBox2" class="box" runat="server"></asp:TextBox> <br /> <br />
<asp:Label ID="Label3" class="caption" runat="server" Text="Skill Name"></asp:Label>
<asp:TextBox ID="TextBox3" class="box" runat="server"></asp:TextBox> <br /> <br />
<asp:Button ID="Button1" class="box" runat="server" Text="Insert"
onclick="Button1_Click" /> <br /><br /><br />

Resources