So here in my application I have 2 dropdowns, 4 labels and a gridview. The Medication Type drop list here with the text PO Meds is supposed to generate the number you see between the 2 drop lists, then based on that number, pull all of the records in the medications table with that number as an ID. The medications should populate in the dropdown marked Medication. The first time I run the application it pulls up the correct information but if I try changing that information, instead of the medication dropdown refilling with the new query information it just adds it to the medication droplist.
here are my 2 droplist and code:
HTML
<td>
<asp:DropDownList ID="ddlMedType" runat="server" DataSourceID="sdsMedType" DataTextField="MedType" DataValueField="MedType" AutoPostBack="True" OnSelectedIndexChanged="ddlMedType_SelectedIndexChanged" AppendDataBoundItems="True">
<asp:ListItem Selected="True">Select Medication Type</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="sdsMedType" runat="server" ConnectionString="<%$ ConnectionStrings:SiteSqlServer2 %>" SelectCommand="SELECT [num], [MedType] FROM [pharm_medication_Type]"></asp:SqlDataSource>
<asp:Label ID="lblMedType" runat="server" Visible="true"/>
</td>
<td>
<asp:DropDownList ID="ddlMedication" runat="server" AppendDataBoundItems="True" AutoPostBack="True" OnSelectedIndexChanged="ddlMedication_SelectedIndexChanged" >
<asp:ListItem Selected="True">Choose A Medication</asp:ListItem>
</asp:DropDownList>
</td>
.CS
protected void ddlMedType_SelectedIndexChanged(object sender, EventArgs e)
{
string strMedType = ddlMedType.SelectedValue;
using (SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer2"].ConnectionString))
{
if (ddlMedType.SelectedValue != "Select Medication Type")
{
SqlCommand cmd1 = new SqlCommand("SELECT [num] from [pharm_medication_Type] where [MedType] = #MedType", conn1);
cmd1.Parameters.AddWithValue("#MedType", strMedType);
conn1.Open();
using (SqlDataReader reader2 = cmd1.ExecuteReader())
{
while (reader2.Read())
{
int strNum = reader2.GetInt32(0);
lblMedType.Text = Convert.ToString(strNum);
}
}
string strMedTypeID = lblMedType.Text;
SqlCommand cmd2 = new SqlCommand("Select [MedType_ID], [MedName] from [pharm_medications] where [MedType_ID] = #MedTypeID", conn1);
cmd2.Parameters.AddWithValue("#MedTypeID", strMedTypeID);
ddlMedication.DataSource = cmd2.ExecuteReader();
lblMedType.Text = string.Empty;
ddlMedication.DataTextField = "MedName";
ddlMedication.DataValueField = "MedName";
ddlMedication.DataBind();
ddlMedType.DataBind();
lblMedType.DataBind();
}
}
}
protected void ddlMedication_SelectedIndexChanged(object sender, EventArgs e)
{
string strMedTypeID = lblMedType.Text;
string strMedName = ddlMedication.SelectedValue;
if (ddlMedication.SelectedValue != "Choose A Medication")
{
using (SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer2"].ConnectionString))
{
SqlCommand cmd1 = new SqlCommand(#"SELECT DISTINCT [num], [MedType_ID], [MedName], [MedMin], [MedMax], [ChargingNumber]
FROM [pharm_medications] WHERE [MedType_ID] = #MedTypeID AND [MedName] = #MedName", conn1);
cmd1.Parameters.AddWithValue("#MedTypeID", strMedTypeID);
cmd1.Parameters.AddWithValue("#MedName", strMedName);
conn1.Open();
using (SqlDataReader reader3 = cmd1.ExecuteReader())
{
while (reader3.Read())
{
int myNum = reader3.GetInt32(0);
int strMyMedTypeID = reader3.GetInt32(1);
string strMyMedName = reader3.GetString(2);
string strMedMin = reader3.GetString(3);
string strMedMax = reader3.GetString(4);
string strChargingNumber = reader3.GetString(5);
lblAutoMin.Text = strMedMin;
lblAutoMax.Text = strMedMax;
lblAutoChargeNum.Text = strChargingNumber;
}
}
}
}
}
Related
Hello I did build a autocomplete text field for my project:
HTML Coding:
<!-- Autocomplete Function -->
<ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender" runat="server" CompletionSetCount="10" TargetControlID="input_source"
ServiceMethod="GetCompletionList" CompletionInterval="100" EnableCaching="false" MinimumPrefixLength="1">
</ajaxToolkit:AutoCompleteExtender>
<!--Inputfield Autocomplete-->
<asp:TextBox autocomplete="on" id="input_source" OnTextChanged="input_source_TextChanged" runat ="server" class="form-control" placeholder="Please enter"></asp:TextBox>
Code behind C#:
//Autocomplete Field
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCompletionList(string prefixText, int count)
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = lr_sqlserver;
using (SqlCommand com = new SqlCommand())
{
com.CommandText = "SELECT TOP 5 Source FROM" + " " + selected_table + " " + "WHERE Source like '%' + #Search + '%'";
com.Parameters.AddWithValue("#Search", prefixText);
com.Connection = con;
con.Open();
List<string> suggestions = new List<string>();
using (SqlDataReader sdr = com.ExecuteReader())
{
while (sdr.Read())
{
suggestions.Add(sdr["Source"].ToString());
}
}
con.Close();
return suggestions;
}
}
}
Now I want to call the following function everytime I select a suggestion from the autocomplete function. Is something like this possible?
protected void input_source_TextChanged(object sender, EventArgs e)
{
string source = input_source.Text;
using (
SqlConnection com = new SqlConnection())
{
//SQL Server
com.ConnectionString = lr_sqlserver;
//Conncection establish
com.Open();
//Get SQL Information
SqlCommand select = new SqlCommand("select target from " + selected_table + " where source = #param", com);
select.Parameters.AddWithValue("#param", source);
string result;
result = (string)select.ExecuteScalar();
if (result != null)
{
input_target.Text = result;
}
}
}
You would need to put your TextBox inside an UpdatePanel and on the TextBox set AutoPostBack="True"
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox autocomplete="on" id="input_source" OnTextChanged="input_source_TextChanged" runat ="server" class="form-control" placeholder="Please enter" AutoPostBack="True"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
I have a function(PopulateStudents) that populates a dropdownlist with results from a database. This function is called on two different occasions: When a query string with id is provided, and in an onselectedindexchanged event. Basically, if an ID is provided from the URL, then get a database record of a student's ID, which contains semesterID and courseID. Then, all DDLs are populated based on the studentID.
If there is no ID in the URL, the user selects a semester from a DDL. Then the course DDL is populated based on the semester ID selected in the semester DDL. Then, the student DDL is populated based on the selected course.
The problem is that the PopulateStudent function works fine when no ID is provided in the query string and the user has to select the semester and then course. When the ID is provded in the query string, the PopulateStudents function does not work. The function throws an error that says Invalid attempt to call FieldCount when reader is closed. What is wrong with my code?
Here is the aspx.cs file:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
GetStudentScores(Convert.ToInt32(Request.QueryString["id"]));
string connString;
connString = RetrieveConnectionString();
SqlConnection conn = new SqlConnection(connString);
try
{
using (conn)
{
conn.Open();
SqlCommand cmd = new SqlCommand("dbo.GetEnrolleeDetails", conn);
cmd.Parameters.Add("#enrollmentID", System.Data.SqlDbType.Int);
cmd.Parameters["#enrollmentID"].Value = Convert.ToInt32(Request.QueryString["id"]);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
int semesterID = Convert.ToInt32(reader["semesterId"]);
int courseID = Convert.ToInt32(reader["courseId"]);
PopulateCourses(semesterID);
PopulateStudents(courseID);
DDSemester.SelectedValue = Convert.ToString(semesterID);
DDCourse.SelectedValue = Convert.ToString(courseID);
DDStudent.SelectedValue = Request.QueryString["ID"];
}
}
catch (Exception err)
{
lblStatus.Text = err.Message;
}
finally
{
conn.Close();
conn.Dispose();
}
}
}
}
protected void DDCourse_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
PopulateStudents(Convert.ToInt32(DDCourse.SelectedValue));
}
}
protected void DDStudent_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
GetStudentScores(Convert.ToInt32(DDStudent.SelectedValue));
}
}
protected void DDSemester_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
PopulateCourses(Convert.ToInt32(DDSemester.SelectedValue));
}
}
private void PopulateCourses(int semesterID)
{
string connString;
connString = RetrieveConnectionString();
SqlConnection conn = new SqlConnection(connString);
try
{
using (conn)
{
conn.Open();
SqlCommand cmd = new SqlCommand("dbo.GetSemesterCourses", conn);
cmd.Parameters.Add("#semesterID", System.Data.SqlDbType.Int);
cmd.Parameters["#semesterID"].Value = semesterID;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
DDCourse.DataSource = cmd.ExecuteReader();
DDCourse.DataTextField = "courseName";
DDCourse.DataValueField = "courseId";
DDCourse.DataBind();
}
}
catch (Exception err)
{
lblStatus.Text = err.Message;
}
finally
{
conn.Close();
conn.Dispose();
}
}
private void PopulateStudents(int courseID)
{
string connString;
connString = RetrieveConnectionString();
SqlConnection conn = new SqlConnection(connString);
try
{
using (conn)
{
conn.Open();
SqlCommand cmd = new SqlCommand("dbo.CourseEnrollment", conn);
cmd.Parameters.Add("#courseId", System.Data.SqlDbType.Int);
cmd.Parameters["#courseId"].Value = courseID;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
DDStudent.DataSource = cmd.ExecuteReader();
DDStudent.DataTextField = "fullName";
DDStudent.DataValueField = "enrollmentId";
this.DataBind();
}
}
catch (Exception err)
{
lblStatus.Text = err.Message;
}
finally
{
conn.Close();
conn.Dispose();
}
}
Here is the asp:
<asp:Label ID="Label1" runat="server" Text="Semester:"></asp:Label>
<asp:DropDownList ID="DDSemester" runat="server" AutoPostBack="True" AppendDataBoundItems="true" DataSourceID="SqlDataSource1" DataTextField="semesterName" DataValueField="semesterId" OnSelectedIndexChanged="DDSemester_SelectedIndexChanged">
<asp:ListItem Text="Select a Semester"></asp:ListItem>
</asp:DropDownList><br />
<asp:Label ID="Label15" runat="server" Text="Course:"></asp:Label>
<asp:DropDownList ID="DDCourse" runat="server" AutoPostBack="True" AppendDataBoundItems="true" OnSelectedIndexChanged="DDCourse_SelectedIndexChanged">
<asp:ListItem Text="Select a Course"></asp:ListItem>
</asp:DropDownList><br />
<asp:Label ID="Label16" runat="server" Text="Student"></asp:Label>
<asp:DropDownList ID="DDStudent" runat="server" AutoPostBack="true" AppendDataBoundItems="true" OnSelectedIndexChanged="DDStudent_SelectedIndexChanged">
<asp:ListItem Text="Select a Student"></asp:ListItem>
</asp:DropDownList><br />
Thanks for your time.
There was actually one difference between the PopulateCourses and PopulateStudents functions that I didn't notice. In courses, I used DDCourse.DataBind() and in students I used this.DataBind().
In the populatestudents function, changing this.DataBind() to DDStudent.DataBind() fixed my problem.
im using asp.net and c#
im using 2 dropdownlist like dd1,dd2
how to fill 2nd dropdownlist dd2 by dd1 onselectindexchanged
my code is,
<asp:DropDownList ID="ddMedType" runat="server" CssClass="drop" AutoPostBack="true" OnSelectedIndexChanged="ddMedType_SelectedIndexChanged">
<asp:ListItem Value="0">-Select-</asp:ListItem>
<asp:ListItem Value="Tablet">Tablet</asp:ListItem>
<asp:ListItem Value="Tonic">Tonic</asp:ListItem>
<asp:ListItem Value="Capsules">Capsules</asp:ListItem>
<asp:ListItem Value="DispoTab">Disposable Tablet</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddMedName" runat="server" CssClass="drop" >
<asp:ListItem Value="0">-Select-</asp:ListItem>
</asp:DropDownList>
protected void ddMedType_SelectedIndexChanged(object sender, EventArgs e)
{
string MedType = ddMedType.SelectedItem.Text;
string str = "select MedicineName,MedicineId from MedicineMaster where MedicineType = '" + MedType + "'";
cmd = new SqlCommand(str, con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ddMedName.SelectedValue= reader["MedicineId"].ToString();
}
}
here the condition returns 2 items, but dropdownlist dd2 returns only 1 ...
You are setting the SelectedValue, this does not mean you're adding or removing items in your dropdownlist
DataTable medicines= new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("select MedicineName,MedicineId from MedicineMaster where MedicineType = '" + MedType + "'", con);
adapter.Fill(subjects);
ddMedName.DataSource = subjects;
ddMedName.DataTextField = "MedicineName";
ddMedName.DataValueField = "MedicineId";
ddMedName.DataBind();
}
catch (Exception ex)
{
// Handle the error
}
}
// Add the initial item - you can add this even if the options from the
// db were not successfully loaded
ddMedName.Items.Insert(0, new ListItem("-Select-", "0"));
You can also do it with the reader as follows:
ddMedName.Items.Clear();
ddMedName.Items.Add(new ListItem("-Select-", "0"));
while (reader.Read())
{
ddMedName.Items.Add(new ListItem(reader["MedicineName"].ToString(), reader["MedicineId"].ToString());
}
Try add item in the DropdownList..
DropDownList1.Items.Add(new ListItem(reader["MedicineId"].ToString(), reader["MedicineId"].ToString()));
Here is one solution may help you:
protected void ddMedType_SelectedIndexChanged(object sender, EventArgs e)
{
string MedType = ddMedType.SelectedItem.Text;
string str = "select MedicineName,MedicineId from MedicineMaster where MedicineType = '" + MedType + "'";
cmd = new SqlCommand(str, con);
SqlDataReader reader = cmd.ExecuteReader();
ddMedName.DataSource = reader;
ddMedName.DataTextField = "MedicineName";
ddMedName.DataValueField = "MedicineId";
ddMedName.DataBind();
}
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;
}
i m using following code to populate dropdownlist dynamically...
i want that value should be the subject id and text should be the sub_desc...but code is not working the value does not contain the sub_ids...so whats wrong with the code??
(sub_id is integer field)
public void Populate()
{
string ConnectionString = (string)ConfigurationManager.AppSettings["ConnectionString"];
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand popCmd = new SqlCommand("select sub_id,sub_desc from subject", conn);
try
{
conn.Open();
ddlSub.Items.Clear();
SqlDataReader subs;
subs = popCmd.ExecuteReader();
ddlSub.DataSource = subs;
ddlSub.DataValueField = "sub_id";
ddlSub.DataTextField = "sub_desc";
ddlSub.DataBind();
conn.Close();
}
catch (Exception ex)
{
lblMsg.Visible = true;
lblMsg.Text = ex.ToString();
}
}
thanx...
You can set AppendDataBoundItems="true" to ensure data bound items do not clear manually inserted list items.
<asp:DropDownList ID="DropDownList" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="--Select Subject--" Text="--Select Subject--" Selected="true"></asp:ListItem>
</asp:DropDownList>
You can also accomplish this in the code behind.
...
dropSub.Items.Add(new ListItem("--Select Subject--", "0"));
dropSub.AppendDataBoundItems = true;
SqlDataReader subs;
subs = popCmd.ExecuteReader();
ddlSub.DataSource = subs;
ddlSub.DataValueField = "sub_id";
ddlSub.DataTextField = "sub_desc";
ddlSub.DataBind();
conn.Close();
...
You can add you default after databinding. You will need to insert at an index of 0 though rather than Add.