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.
Related
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();
}
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;
}
}
}
}
}
I have some dynamically generated checklist-items. When user deletes them, confirmation box should appear. How can i do that ?
protected void btndelete_Click(object sender, EventArgs e)
{
try
{
string conn = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
SqlConnection con = new SqlConnection(conn);
con.Open();
check:
if (CheckBoxList1.SelectedItem != null)
{
foreach (ListItem l in CheckBoxList1.Items)
{
if (l.Selected)
{
SqlCommand cmd = new SqlCommand("Drop Table " + l, con);
cmd.ExecuteNonQuery();
Label4.ForeColor = Color.Red;
Label4.Text = " PaperSet Deleted successfully";
CheckBoxList1.Items.Remove(l);
papersetlist.Items.Remove(l);
Psetlist.Items.Remove(l);
goto check;
}
}
}
con.Close();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This is delete button event code.
You just need to write something like this
<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete"
OnClientClick="return confirm('Are you certain you want to delete this item?');">
</asp:LinkButton>
Please inspect my C# code below and let me know where I am going wrong. Here is what I am experiencing:
1.) If I empty the SendReport column in SQL Server and load the page, the second row of the SendReport automatically gets populated with a 1.
2.) I can place a checkmark, click the button and the SendReport values successfully populate in SQL Server. However, if I uncheck any of them and click the button, none of the values change from 1 to 0. Please help!
$<asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList>
<br />
<asp:Button ID="Button1" runat="server" Text="Save Changes" OnClick="Button1_Click" />
<br />
BACKPAGE:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindCheckBoxList();
}
}
// Setting up the ConnectionString
public string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["IPdataConnectionString"].ConnectionString;
}
// Binding the CheckBoxList with Data
private void BindCheckBoxList()
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(GetConnectionString());
try
{
connection.Open();
string sqlStatement = "SELECT Partner, ID, SendReport FROM Rorts";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
CheckBoxList1.DataSource = dt;
CheckBoxList1.DataTextField = "Partner"; // the items to be displayed in the list items
CheckBoxList1.DataValueField = "SendReport"; // the id of the items displayed
CheckBoxList1.DataBind();
//Setting the Selected Items in the ChecBoxList based from the value in the database
//to do this, lets iterate to each items in the list
for (int i = 0; i < dt.Rows.Count; i++)
{
if (!string.IsNullOrEmpty(dt.Rows[i]["SendReport"].ToString()))
{
CheckBoxList1.Items[i].Selected = Convert.ToBoolean(dt.Rows[i]["SendReport"]);
}
}
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}
// Creating the Method for Saving the CheckBoxList Selected Items to the database
private void Update(string name, bool SendReport)
{
SqlConnection connection = new SqlConnection(GetConnectionString());
SqlCommand cmd;
string sqlStatement = string.Empty;
try
{
// open the Sql connection
connection.Open();
sqlStatement = "UPDATE Rorts SET SendReport = #SendReport WHERE Partner = #Partner";
cmd = new SqlCommand(sqlStatement, connection);
cmd.Parameters.AddWithValue("#Partner", name);
cmd.Parameters.AddWithValue("#SendReport", SendReport);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert/Update Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
// close the Sql Connection
connection.Close();
}
}
// Calling the Method for Saving the state of CheckBoxList selected items
protected void Button1_Click(object sender, EventArgs e)
{
string PartnerName = string.Empty;
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected)
{
PartnerName = CheckBoxList1.Items[i].Text;
Update(PartnerName, CheckBoxList1.Items[i].Selected);
}
}
//ReBind the List to retain the selected items on postbacks
BindCheckBoxList();
}
It looks like the issue is due to the if block below from the Button1 click event handler. The result is that only the check boxes that are checked have the values persisted to the database.
if (CheckBoxList1.Items[i].Selected)
{
PartnerName = CheckBoxList1.Items[i].Text;
Update(PartnerName, CheckBoxList1.Items[i].Selected);
}
You can just remove the if statement and persist all of the values or add logic to only persist those that have changed.
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.