I have been following the following example to create some cascading dropdowns in a web application. The example does not use jquery and I would like to stick with this for now.
https://www.aspsnippets.com/Articles/Populate-Cascading-DropDownList-from-Database-in-ASPNet-Example.aspx
I am having trouble getting my second dropdown to populate a list using the result from the first. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CategorySelect.Items.Clear();
CategorySelect.Items.Add(new ListItem("--Select Activity--", ""));
CategorySelect.AppendDataBoundItems = true;
String strConnString = ConfigurationManager
.ConnectionStrings["iSAMSConnectionString"].ConnectionString;
String strQuery = "select TblActivityManagerFolderID, txtName from dbo.TblActivityManagerFolder";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
CategorySelect.DataSource = cmd.ExecuteReader();
CategorySelect.DataTextField = "txtName";
CategorySelect.DataValueField = "TblActivityManagerFolderID";
CategorySelect.DataBind();
}
finally
{
con.Close();
con.Dispose();
}
}
}
protected void ActivitySelect_SelectedIndexChanged(object sender, EventArgs e)
{
ActivitySelect.Items.Clear();
ActivitySelect.Items.Add(new ListItem("--Select Activity--", ""));
ActivitySelect.AppendDataBoundItems = true;
String strConnString = ConfigurationManager
.ConnectionStrings["iSAMSConnectionString"].ConnectionString;
String strQuery = "select txtName, TblActivityManagerGroupID from dbo.TblActivityManagerGroup " +
"where intFolder=#txtName";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#txtName",
CategorySelect.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
ActivitySelect.DataSource = cmd.ExecuteReader();
ActivitySelect.DataTextField = "txtName";
ActivitySelect.DataValueField = "TblActivityManagerGroupID";
ActivitySelect.DataBind();
if (ActivitySelect.Items.Count > 1)
{
ActivitySelect.Enabled = true;
}
else
{
ActivitySelect.Enabled = false;
}
}
finally
{
con.Close();
con.Dispose();
}
}
I am using 2 tables.
TblActivityManagerFolder where I am using 2 fields - TblActivityManagerFolderID and txtName
TblActivityManagerGroup where I am using 2 fields - intFolder (which joins to TblActivityManagerFolderID) and txtName
My first drop down populates exactly as expected, but when I make a selection nothing at all happens in the 2nd dropdown.
Additional Code:
<asp:SqlDataSource ID="iSAMS" runat="server" ConnectionString="<%$ ConnectionStrings:iSAMSConnectionString %>"
SelectCommand="SELECT [blnActive], [TblActivityManagerFolderID], [txtName] FROM [TblActivityManagerFolder] WHERE ([intActivity] = #intActivity)">
<SelectParameters>
<asp:Parameter DefaultValue="34" Name="intActivity" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</div>
<div class="auto-style18">
<asp:DropDownList ID="CategorySelect" runat="server" DataTextField="txtName" DataValueField="TblActivityManagerFolderID"
OnSelectedIndexChanged="ActivitySelect_SelectedIndexChanged" CssClass="newStyle1">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="CategorySelect"
ErrorMessage="Please select your answer" style="text-align: left; font-weight: 700; color: #FF0000; font-size: medium;">!</asp:RequiredFieldValidator>
</div>
<br />
<div class="auto-style19">
<div class="auto-style20">
Please select the activity undertaken from the pick list:
<asp:DropDownList ID="ActivitySelect" runat="server" DataSourceID="iSAMSActivity" DataTextField="txtName" DataValueField="TblActivityManagerGroupId" CssClass="newStyle1" OnSelectedIndexChanged="ActivitySelect_SelectedIndexChanged">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="ActivitySelect"
ErrorMessage="Please select your answer" style="text-align: left; font-weight: 700; color: #FF0000; font-size: medium;">!</asp:RequiredFieldValidator>
<asp:SqlDataSource ID="iSAMSActivity" runat="server" ConnectionString="<%$ ConnectionStrings:iSAMSConnectionString %>" SelectCommand="SELECT [txtName], [intActivity], [intFolder], [TblActivityManagerGroupId] FROM [TblActivityManagerGroup] WHERE ([intFolder] = #intFolder)">
<SelectParameters>
<asp:ControlParameter ControlID="CategorySelect" Name="intFolder" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
I am also posting back the results so I can see if this is working using:
protected void Button1_Click(object sender, EventArgs e)
{
var activity = CategorySelect.DataTextField;
var CoCActivity = ActivitySelect.DataTextField;
var OtherSkills = SkillsTextBox.Text;
var ExtraDev = DevTextBox.Text;
var OtherActivities = OtherActivitiesTextBox.Text;
OutputLabel.Text = activity + "<br/>" + CoCActivity + "<br/>" + OtherSkills + "<br/>" + ExtraDev + "<br/>" + OtherActivities;
}
When it is posting back, it is producing an integer rather than the label in the dropdown list. Can this be changed so it post backs the actual text?
Set the AutoPostBack property of the DropdownList to True. If you dont set it, the event would be only be triggered server side when other events force a postback (a button click or similar)
Related
I am trying to update a single record in a DataList. I have chosen the DataList type so that I can have a horizontal row with many records on the same page, can use the page to take attendance from a pre-determined list of people, but I want to update as I go. I will be using volunteers to take attendance and don't want to force the users to click save after they are finished (They may get distracted and forget to do so). So, each check box marks a person present. Or unchecking marks them absent.
Here is my CSHTML page:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="AttendanceTaking.aspx.cs" Inherits="AtChurch.AttendanceTaking" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<style>.ChkBoxClass input {width:25px; height:25px;}
.auto-style1 {
width: 32px;
}
.auto-style2 {
width: 183px;
}
</style>
<table>
<tr>
<td class="auto-style2"><strong>Take Attendance</strong></td>
<td class="auto-style1">Date:</td>
<td>
<strong>
<asp:Label ID="lblAttendanceDate" runat="server"></asp:Label>
</strong>
</td>
<td>
Attendance Group:</td>
<td>
<strong>
<asp:Label ID="lblAttendanceGroup" runat="server" ></asp:Label>
</strong>
</td>
</tr>
</table>
<p>
<asp:HiddenField ID="HiddenAttendanceDate" runat="server" />
<asp:HiddenField ID="HiddenSoCID" runat="server" />
</p>
<p>
<asp:DataList RepeatDirection="Horizontal" RepeatColumns="6" ID="DataList1" runat="server" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="DataList1_SelectedIndexChanged" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Both">
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<ItemStyle ForeColor="#000066" />
<ItemTemplate>
<asp:CheckBox ID="CheckBoxPresent" runat="server" RowNumber='<%# Eval("RowNumber") %>' AttendanceID='<%# Eval("AttendanceID") %>' PeopleId='<%# Eval("PeopleID") %>' Text='<%# Eval("CheckBoxPresent") %>' Checked='<%# Eval("CheckBoxPresent").ToString().Equals("1") %>' CssClass="ChkBoxClass" OnCheckedChanged="CheckBoxPresent_CheckedChanged" AutoPostBack="true" />
<asp:Label ID="RowNumber" runat="server" Text='<%# Eval("RowNumber") %>' />
<asp:Label ID="FullName" runat="server" Text='<%# Eval("FullName") %>' />
<asp:Label ID="PeopleID" runat="server" Text='<%# Eval("PeopleID") %>' />
<asp:Label ID="AttendanceID" runat="server" Text='<%# Eval("AttendanceID") %>' ></asp:Label>
<asp:Label ID="AttendLabel" runat="server" Text="      "></asp:Label> <br />
<br />
</ItemTemplate>
<SelectedItemStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<FooterTemplate>
:
</FooterTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AtChurchConString %>" SelectCommand="sp_AttendanceTaking" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="ChurchID" DefaultValue="0" Name="ChurchID" PropertyName="Value" />
<asp:ControlParameter ControlID="HiddenSoCID" DefaultValue="0" Name="HiddenSoCID" PropertyName="Value" />
<asp:Parameter DefaultValue="1" Name="Select" Type="Int32" />
<asp:ControlParameter ControlID="HiddenAttendanceDate" DefaultValue="" Name="AttendanceDate" PropertyName="Value" Type="DateTime" />
<%--<asp:ControlParameter ControlID="CheckBoxPresent" DefaultValue="0" Name="CheckBoxPresent" PropertyName="Value" />--%>
<%-- <asp:ControlParameter ControlID="AttendanceID" DefaultValue="0" Name="AttendanceID" PropertyName="Value" />--%>
<%--<asp:ControlParameter ControlID="PeopleID" DefaultValue="0" Name="PeopleID" PropertyName="Value" />--%>
</SelectParameters>
</asp:SqlDataSource>
<asp:HiddenField ID="ChurchID" runat="server" />
</p>
<p>
</p>
</asp:Content>
And here is my CS page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Web.SessionState;
namespace AtChurch
{
public partial class AttendanceTaking : System.Web.UI.Page
{
private static string strcon = WebConfigurationManager.ConnectionStrings["AtChurchConString"].ConnectionString;
// Need these for Security
public string strRole, strChurchID, strAttGroup, strAttDate;
public bool ValidUser { get; private set; }
// Checkbox Checked?
protected void CheckBoxPresent_CheckedChanged(object sender, EventArgs e)
{
//start of checkbox
CheckBox ChkBxPresent = sender as CheckBox;
Boolean ChkBxPresentState = ChkBxPresent.Checked;
//DataList1.DataBind();
foreach (DataListItem itm in DataList1.Items)
{
if (itm.ItemType == ListItemType.Item )
{
string strPeopleID = ((Label)itm.FindControl("PeopleID")).Text;
string strAttendanceID = ((Label)itm.FindControl("AttendanceID")).Text;
Response.Write(strPeopleID);
Response.End();
//string strAttID = "";
//strAttID = ((DataBoundLiteralControl)item.Controls[1]).Text;
if (ChkBxPresentState == true)
{
Response.Write("Let's Insert it...");
Response.Write(strPeopleID);
Response.End();
}
else
{
//Response.Write("Let's Remove it...");
//Response.End();
SqlConnection con = new SqlConnection(strcon);
// First let's delete this Groups Data
SqlCommand cmdDelete = new SqlCommand("sp_AttendanceTaking", con);
cmdDelete.CommandType = CommandType.StoredProcedure;
//cmdDelete.Parameters.Add(new SqlParameter("#HiddenSoCID", SqlDbType.Int));
cmdDelete.Parameters.Add(new SqlParameter("#AttendanceID", SqlDbType.Int));
//cmdDelete.Parameters.Add(new SqlParameter("#ChurchID", SqlDbType.Int));
//cmdDelete.Parameters.Add(new SqlParameter("#AttendanceDate", SqlDbType.DateTime));
cmdDelete.Parameters.Add(new SqlParameter("#CheckBoxPresent", SqlDbType.Int));
//cmdDelete.Parameters.Add(new SqlParameter("#PeopleID", SqlDbType.Int));
// Convert Strings to Int where needed
if (Int32.TryParse(strAttendanceID.ToString(), out int intAttendanceID)) { }
Response.Write(intAttendanceID);
Response.Write("-");
Response.Write(1);
Response.End();
cmdDelete.Parameters["#AttendanceID"].Value = intAttendanceID;
cmdDelete.Parameters["#CheckBoxPresent"].Value = 0;
con.Open();
cmdDelete.ExecuteNonQuery();
con.Close();
// End delete data
}
}
}
//end of checkbox
}
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
if (!IsPostBack)
{
// Get Attendance Group ID from the Attendance page.
//if (Request.QueryString["SoCID"].ToString() != null && Request.QueryString["SoCID"].ToString() != null)
string SoCID = Server.UrlDecode(Request.QueryString["SoCID"]);
string AttendanceDate = Server.UrlDecode(Request.QueryString["AttendanceDate"]);
// Response.Write("ok?"+AttendanceDate);
// Response.End();
if (SoCID != null && AttendanceDate != null)
{
strAttGroup = SoCID;
HiddenSoCID.Value = strAttGroup;
lblAttendanceGroup.Text = strAttGroup;
strAttDate = AttendanceDate;
HiddenAttendanceDate.Value = strAttDate;
lblAttendanceDate.Text = strAttDate;
//strAttDate = Request.QueryString["AttendanceDate"].ToString();
//Response.Write(strAttGroup);
//Response.Write(strAttDate);
//Response.End();
}
else
{
//Response.Write("error");
Response.Redirect("Attendance.aspx");
Response.End();
}
}
// Security Start
if (Session["Role"] is null && Session["ChurchID"] is null)
{
Response.Redirect("Login.aspx");
return;
}
if (Session["Role"] != null && Session["ChurchID"] != null)
{
if (!string.IsNullOrEmpty(Session["Role"].ToString()))
{
strRole = Session["Role"].ToString();
strChurchID = Session["ChurchID"].ToString();
}
}
if (strRole == ("SuperAdmin") || strRole == ("ChurchAdmin"))
{
ValidUser = true;
}
if (ValidUser != true)
{
Response.Redirect("Login.aspx");
}
// Security End
//Populate the ChurchID for Insert
ChurchID.Value = strChurchID;
}
protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button_AttendanceTaker_Command(object sender, CommandEventArgs e)
{
}
}
}
This is just the button code of which I am working with to add or delete using my stored procedure.
protected void CheckBoxPresent_CheckedChanged(object sender, EventArgs e)
{
//start of checkbox
CheckBox ChkBxPresent = sender as CheckBox;
Boolean ChkBxPresentState = ChkBxPresent.Checked;
// I added this to try to compare to to get a specific row for Insert
string BoxIndex = ChkBxPresent.Attributes["RowNumber"];
//DataList1.DataBind();
foreach (DataListItem itm in DataList1.Items)
{
// I added this to try to compare to within the Item List
string ItmIndex = ((Label)itm.FindControl("RowNumber")).Text;
if (itm.ItemType == ListItemType.Item)
{
// Let's gather the parameter data needed
string strPeopleID = ChkBxPresent.Attributes["PeopleId"];
string strAttendanceID = ChkBxPresent.Attributes["AttendanceID"];
string strCheckBoxPresent = ChkBxPresent.Attributes["IsChecked"];
string strAttGroupID = ((Label)itm.FindControl("SoCID")).Text;
string strAttendanceDate = ((Label)itm.FindControl("AttendanceDate")).Text;
// Here is what we do if the box is checked...
// I used this to try and compare the values. It showed the one I wanted to
// compare to but the ItmIndex only returned odd rows. So I don't match somtimes
//Response.Write("BoxIdx=");
//Response.Write(BoxIndex);
//Response.Write("and ItmIdx=");
//Response.Write(ItmIndex);
// I added the compare of ItmIndex == BoxIndex but it was not consistent. Again it was only returning odd
// numbers and no even numbers to compare to for some reason.
if (ChkBxPresentState == true)
{
string strAction = "ADD";
//Response.Write("Add BoxIdx=");
//Response.Write(BoxIndex);
//Response.Write("and ItmIdx=");
//Response.Write(ItmIndex);
SqlConnection con = new SqlConnection(strcon);
//Response.Write("Let's Insert it...");
//Response.Write("PeopleID");
//Response.Write(strPeopleID);
//Response.Write("ChurchID");
//Response.Write(strChurchID);
//Response.Write("GroupID");
//Response.Write(strAttGroupID);
//Response.Write("AttDate");
//Response.Write(strAttendanceDate);
//Response.Write("Action");
//Response.Write(strAction);
//Response.End();
SqlCommand cmdInsertData = new SqlCommand("sp_AttendanceTaking", con);
cmdInsertData.CommandType = CommandType.StoredProcedure;
cmdInsertData.Parameters.Add(new SqlParameter("#AttGroupID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar));
cmdInsertData.Parameters.Add(new SqlParameter("#PeopleID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#ChurchID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#AttendanceDate", SqlDbType.DateTime));
// Convert Strings to Int where needed
if (Int32.TryParse(strAttGroupID.ToString(), out int intGroupID)) { }
if (Int32.TryParse(strPeopleID.ToString(), out int intPeopleID)) { }
if (Int32.TryParse(strChurchID.ToString(), out int intChurchID)) { }
//Response.Write(intAttendanceID);
//Response.Write("-");
//Response.Write(strAction);
//Response.End();
cmdInsertData.Parameters["#AttGroupID"].Value = intGroupID;
cmdInsertData.Parameters["#Action"].Value = strAction;
cmdInsertData.Parameters["#PeopleID"].Value = intPeopleID;
cmdInsertData.Parameters["#ChurchID"].Value = intChurchID;
cmdInsertData.Parameters["#AttendanceDate"].Value = strAttendanceDate;
con.Open();
cmdInsertData.ExecuteNonQuery();
con.Close();
}
else
{
string strAction = "DEL";
//Response.Write("DEL BoxIdx=");
//Response.Write(BoxIndex);
//Response.Write("and ItmIdx=");
//Response.Write(ItmIndex);
//Response.Write(" |");
// Here is what we do if the Box is unchecked
//Response.Write("Let's Remove it...");
//Response.Write(strPeopleID);
//Response.Write("aID");
//Response.Write(strAttendanceID);
//Response.Write("checkBoxPresent:");
//Response.Write(strCheckBoxPresent);
//Response.End();
SqlConnection con = new SqlConnection(strcon);
// First let's delete this Groups Data
SqlCommand cmdDelete = new SqlCommand("sp_AttendanceTaking", con);
cmdDelete.CommandType = CommandType.StoredProcedure;
cmdDelete.Parameters.Add(new SqlParameter("#AttendanceID", SqlDbType.Int));
cmdDelete.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar));
// Convert Strings to Int where needed
if (Int32.TryParse(strAttendanceID.ToString(), out int intAttendanceID)) { }
//Response.Write(intAttendanceID);
//Response.Write("-");
//Response.Write(strAction);
//Response.End();
cmdDelete.Parameters["#AttendanceID"].Value = intAttendanceID;
cmdDelete.Parameters["#Action"].Value = strAction;
con.Open();
cmdDelete.ExecuteNonQuery();
con.Close();
// End delete data
}
}
}
//end of checkbox
}
It's obviously not complete as I'm just trying to get it to show the right data. I did a test of the delete portion (When the box is unchecked) and it did not delete a specific record because the EventArgs returns all the checkbox values. If I change it to DataListItemEventArgs it returns specific rows but then I lose the functionality of the checkbox on check. I think I need to separate these but I am not sure how to accomplish this task.
Here is the functionality I am going for:
1. Setup the date and retrieve any attendance if already taken.
Image of form that loads the AttendanceTaker
And a sample of the page I am going for with a large checkbox so it can be used on a tablet.
Sample of AttendanceTaker page
I rewrote the code using the idea from selected answer. This was the code that ended up working.
// Checkbox Checked?
protected void CheckBoxPresent_CheckedChanged(object sender, EventArgs e)
{
CheckBox ChkBxPresent = sender as CheckBox;
Boolean ChkBxPresentState = ChkBxPresent.Checked;
if (Int32.TryParse(ChkBxPresent.Attributes["AttendanceID"].ToString(), out int intAttendanceID)) { }
// Let's gather the parameter data needed
string strPeopleID = ChkBxPresent.Attributes["PeopleId"];
string strAttendanceID = ChkBxPresent.Attributes["AttendanceID"];
string strCheckBoxPresent = ChkBxPresent.Attributes["IsChecked"];
string strAttGroupID = ChkBxPresent.Attributes["SoCID"];
string strAttendanceDate = ChkBxPresent.Attributes["AttendanceDate"];
if (intAttendanceID == 0) // Add Attendance Record it does not exist and was checked
{
string strAction = "ADD";
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmdInsertData = new SqlCommand("sp_AttendanceTaking", con);
cmdInsertData.CommandType = CommandType.StoredProcedure;
cmdInsertData.Parameters.Add(new SqlParameter("#AttGroupID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar));
cmdInsertData.Parameters.Add(new SqlParameter("#PeopleID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#ChurchID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#AttendanceDate", SqlDbType.DateTime));
// Convert Strings to Int where needed
if (Int32.TryParse(strAttGroupID.ToString(), out int intGroupID)) { }
if (Int32.TryParse(strPeopleID.ToString(), out int intPeopleID)) { }
if (Int32.TryParse(strChurchID.ToString(), out int intChurchID)) { }
cmdInsertData.Parameters["#AttGroupID"].Value = intGroupID;
cmdInsertData.Parameters["#Action"].Value = strAction;
cmdInsertData.Parameters["#PeopleID"].Value = intPeopleID;
cmdInsertData.Parameters["#ChurchID"].Value = intChurchID;
cmdInsertData.Parameters["#AttendanceDate"].Value = strAttendanceDate;
con.Open();
cmdInsertData.ExecuteNonQuery();
con.Close();
DataList1.DataBind();
}
else // Delete Attendance Record it was unchecked
{
string strAction = "DEL";
SqlConnection con = new SqlConnection(strcon);
// First let's delete this Groups Data
SqlCommand cmdDelete = new SqlCommand("sp_AttendanceTaking", con);
cmdDelete.CommandType = CommandType.StoredProcedure;
cmdDelete.Parameters.Add(new SqlParameter("#AttendanceID", SqlDbType.Int));
cmdDelete.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar));
cmdDelete.Parameters["#AttendanceID"].Value = intAttendanceID;
cmdDelete.Parameters["#Action"].Value = strAction;
con.Open();
cmdDelete.ExecuteNonQuery();
con.Close();
DataList1.DataBind();
// End delete data
}
////end of checkbox
You can pass the value of the PeopleId (and/or attendanceID) in the checkbox as an attribute and avoid iterating over the DataList.
Your checkbox
<asp:CheckBox ID="CheckBoxPresent" runat="server" PeopleId='<%# Eval("PeopleID") %>' Text='<%# Eval("CheckBoxPresent") %>' Checked='<%# Eval("CheckBoxPresent").ToString().Equals("1") %>' CssClass="ChkBoxClass" OnCheckedChanged="CheckBoxPresent_CheckedChanged" AutoPostBack="true" />
Code behind
string strPeopleID = ChkBxPresent.Attributes["PeopleId"];
Then if it's checked, issue insert command for that ID only, if it's unchecked, issue delete command for that ID.
This was working the other day, not sure what happened but it isn't now and I cant figure it out. The label will only give me one item out of around 20(give or take) distinct items. No matter what I select in my drop down list, it always gives me that same value on the label.
HTML:
<td>
<asp:DropDownList ID="ddlCompanyCode" runat="server" CssClass="Dropdown" AutoPostBack="True" OnSelectedIndexChanged="ddlCompanyCode_SelectedIndexChanged" Width="139px" DataSourceID="CompanyCodeDS" DataTextField="CompanyCode" DataValueField="CompanyCode"></asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="ddlCompanyCode" Display="Dynamic" ErrorMessage="*Please select a drop down list item." ForeColor="#CC0000" ValidationGroup="Submit"></asp:RequiredFieldValidator>
</td>
<td>
<asp:Label ID="lblSourceSyst" runat="server" CssClass="txtLabel" Text="Select Company Code" Width="137px" ></asp:Label>
</td>
<asp:SqlDataSource ID="CompanyCodeDS" runat="server" SelectCommandType="StoredProcedure" ConnectionString="<%$ ConnectionStrings:RptDatamartConnectionString %>" SelectCommand="[AXMap].[SelectCompanyCode_GLSourceCOA]">
</asp:SqlDataSource>
C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlCompanyCode.Items.Add(new ListItem("--Please Select--", ""));
ddlCompanyCode.AppendDataBoundItems = true;
}
}
protected void ddlCompanyCode_SelectedIndexChanged(object sender, EventArgs e)
{
String connectionString = ConfigurationManager.ConnectionStrings["RptDatamartConnectionString"].ConnectionString;
String sqlStoredProc = "RptDatamart.AXMap.SelectCompanyCode_GLSourceCOA";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#CompanyCode", ddlCompanyCode.SelectedItem.Value);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sqlStoredProc;
cmd.Connection = con;
try
{
con.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
lblSourceSyst.Text = dataReader["SourceSystem"].ToString();
}
}
catch (Exception ex)
{
lblStatus.Text = ex.Message;
}
}
And then the stored procedure im trying to use...
ALTER PROCEDURE [AXMap].[SelectCompanyCode_GLSourceCOA]
#CompanyCode varchar(10) = Null,
#SourceSystem nvarchar(255) = Null
AS
BEGIN
SET NOCOUNT OFF;
Select distinct CompanyCode, SourceSystem from [RptDatamart].[AXMap].[GLSourceCOA]
END
my sql might be terribly off, but i would think it would work.
lblSourceSyst.Text = dataReader["SourceSystem"].ToString();
Should be:
lblSourceSyst.Text += dataReader["SourceSystem"].ToString();
I need to get products based on chosen subcategory. Now, it displays all products. How to do this? Here is my code. How to pass Subcategory.Id in button click?
...
<td>Subcategory</td>
<td>
<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="SqlDataSource2" DataTextField="Name" DataValueField="Id">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2"
runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Id], [Name] FROM [SubCategory] WHERE ([IdCategory] = #IdCategory)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="IdCategory" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</td>
</tr>
...
protected void Button1_Click(object sender, EventArgs e)
{
...
SqlCommand command = new SqlCommand("SELECT productName, quantity, price FROM Product JOIN SubCategory ON Product.id_subcategory = SubCategory.id", _connection);
...
}
I'm gonna assume that the DropDownList2 control already contains the subcategory data.
You can get your subcategory ID in Button1_Click event with
DropDownList2.SelectedValue
Assuming that you have the following database table structure:
Product
- Id (PK)
- ProductName
- Quantity
- Price
- MainCatID (FK)
- SubCatID (FK)
- others...
Category
- Id (PK)
- Name
SubCategory
- Id (PK)
- Name
- IdCategory (FK)
Make sure to add the namespace System.Configuration so that you can access your connection string from your web.config file.
Instantiate an SqlConnection class to identify the database connection:
Create methods to display the list of categories and sub categories from their respective drop down list controls
Include an AutoPostBack property to DropDownList1 then set to true so that each time you select an item from the list, it will 'regenerate' a list of sub categories based from the selected category value.
Create an OnSelectedIndexChanged event of DropDownList1 calling the DisplaySubCategories() method.
Create a method that will display list of products based from selected category and sub category values
Include similar process from Step #4 to DropDownList2
Call the two methods inside the page load event.
SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DisplayCategories();
DisplaySubCategories();
}
}
void DisplayCategories()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT Id, Name FROM Category";
SqlDataReader data = cmd.ExecuteReader();
DropDownList1.DataSource = data;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Id";
DropDownList1.DataBind();
con.Close();
}
void DisplaySubCategories(string ID)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT Id, Name FROM SubCategory WHERE IdCategory = #IdCategory";
cmd.Parameters.AddWithValue("#IdCategory", ID);
SqlDataReader data = cmd.ExecuteReader();
DropDownList2.DataSource = data;
DropDownList2.DataTextField = "Name";
DropDownList2.DataValueField = "Id";
DropDownList2.DataBind();
con.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DisplaySubCategories(DropDownList2.SelectedValue);
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
DisplayProducts(DropDownList1.SelectedValue, DropDownList2.SelectedValue);
}
void DisplayProducts(string mainCatID, string subCatID)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = #"SELECT productName, quantity, price FROM Product
WHERE MainCatID = #MainCatID AND SubCatID=#SubCatID";
cmd.Parameters.AddWithValue("#MainCatID", mainCatID);
cmd.Parameters.AddWithValue("#SubCatID", subCatID);
SqlDataReader data = cmd.ExecuteReader();
string result = string.Empty;
while (data.Read())
{
result += "Name = " + Convert.ToString(reader["productName"]) + "; ";
result += "Quantity = " + Convert.ToString(reader["quantity"]) + "; ";
result += "Price = " + Convert.ToString(reader["price"]);
result += "<br />";
}
ReadAllOutput.Text = result;
con.Close();
}
.aspx
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" />
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" />
I removed all the existing SqlDataSource controls because I find them messy.
Update:
You can also declare the method DisplayProducts() inside the Button click event
protected void Button1_Click(object sender, EventArgs e)
{
DisplayProducts(DropDownList1.SelectedValue, DropDownList2.SelectedValue);
}
PS: Some syntax might be incorrect (case-sensitivity) and I'm not using an IDE as of the moment.
I have the following ASP drop-down:
<asp:DropDownList ClientIDMode="Static" ID="ddlMain" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="BY PHYSICIAN" Value="0" Selected="True" />
<asp:ListItem Text="BY LOCATION" Value="1" />
<asp:ListItem Text="BY SPECIALTY" Value="2" />
</asp:DropDownList>
<br /><br />
<asp:DropDownList ClientIDMode="Static" ID="ddlDrillDown" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>
I am trying to make it interactive where if the first select option is changed the second will change as well based on the selection from the first select option.
My C# code looks like this:
public partial class test : System.Web.UI.Page
{
String cString;
SqlConnection Conn;
protected void Page_Load(object sender, EventArgs e) {
PopulatePhysician();
//PopulateSpecialty();
//PopulateLocation();
}
public void PopulatePhysician() {
SqlCommand cmd = new SqlCommand("getPhysicians", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
//cmd.CommandType = Data.CommandType.StoredProcedure
cmd.Connection.Open();
SqlDataReader ddlValues = default(SqlDataReader);
ddlValues = cmd.ExecuteReader();
//if (!IsPostBack) {
ddlDrillDown.DataSource = ddlValues;
ddlDrillDown.DataValueField = "content_id";
ddlDrillDown.DataTextField = "content_title";
ddlDrillDown.DataBind();
//set the default value for the drop down
ListItem Item = new ListItem();
Item.Text = "Select a Physician's Name";
Item.Value = "0";
//Item.Selected = True
ddlDrillDown.Items.Insert(0, Item);
//}
cmd.Connection.Close();
cmd.Connection.Dispose();
}
public void PopulateSpecialty() {
SqlCommand cmd = new SqlCommand("getSpecialties", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();
SqlDataReader ddlValues = default(SqlDataReader);
ddlValues = cmd.ExecuteReader();
//if (!IsPostBack) {
ddlDrillDown.DataSource = ddlValues;
ddlDrillDown.DataValueField = "content_id";
ddlDrillDown.DataTextField = "content_title";
ddlDrillDown.DataBind();
//set the default value for the drop down
ListItem Item = new ListItem();
Item.Text = "Select a Specialty";
Item.Value = "0";
ddlDrillDown.Items.Insert(0, Item);
//}
cmd.Connection.Close();
cmd.Connection.Dispose();
}
public void PopulateLocation() {
SqlCommand cmd = new SqlCommand("getLocations", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();
SqlDataReader ddlValues = default(SqlDataReader);
ddlValues = cmd.ExecuteReader();
//if (!IsPostBack) {
ddlDrillDown.DataSource = ddlValues;
ddlDrillDown.DataValueField = "content_id";
ddlDrillDown.DataTextField = "content_title";
ddlDrillDown.DataBind();
//set the default value for the drop down
ListItem Item = new ListItem();
Item.Text = "Select a Location";
Item.Value = "0";
ddlDrillDown.Items.Insert(0, Item);
cmd.Connection.Close();
cmd.Connection.Dispose();
//}
}
public void ddlMain_SelectedIndexChanged(object sender, System.EventArgs e) {
switch(ddlMain.SelectedItem.Value) {
case "0":
PopulatePhysician();
break;
case "1":
PopulateLocation();
break;
case "2":
PopulateSpecialty();
break;
}
}
}
When the page first loads, PopulatePhysician(); works great by populating the select option. But when I call the SelectedIndexChanged() function, nothing happens.
How can I resolve it? Is the case statement correct?
You haven't added any delegates to the SelectedIndexChanged event.
Add OnSelectedIndexChanged to the parameters in the asp:DropDownList tag, like so:
<asp:DropDownList ClientIDMode="Static" OnSelectedIndexChanged="ddlMain_SelectedIndexChanged" ID="ddlMain" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true" >
EDIT
I just noticed you're actually missing the AutoPostBack event as well - it should be set to true, as updating the selection without submitting the form will not fire a postback event, unless AutoPostBack is set to true.
It needs AutoPostback=true on the Dropdown list
<asp:DropDownList AutoPostback="true" ClientIDMode="Static" ID="ddlMain" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
Remove the If (!IsPostBack) clause from your functions. Check for that in page load, but not in each individual function.
I've created a search function with 3 DropDownLists and a search button. How will I display it on the same page?
Here's my code:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//read sql server connection string from web.config file
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_province ORDER BY PROVINCE_NAME ASC", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlProvince.DataSource = dt;
ddlProvince.DataTextField = "PROVINCE_NAME";
ddlProvince.DataValueField = "PROVINCE_CODE";
ddlProvince.DataBind();
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
PROVINCE_CODE = '" + ddlProvince.SelectedValue + "'", conn);
SqlCommand comm = new SqlCommand("SELECT * FROM emed_city WHERE PROVINCE_CODE =#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#pcode";
param.Value = ddlProvince;
comm.Parameters.Add(param);
}
ddlCity.DataSource = dt;
ddlCity.DataTextField = "CITY_NAME";
ddlCity.DataValueField = "CITY_CODE";
ddlCity.DataBind();
}
protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_city");
using (conn)
{
conn.Open();
PROVINCE_CODE = '" + ddlProvince.SelectedValue + "'", conn);
SqlCommand comm = new SqlCommand("SELECT * FROM emed_doctors_hospitals WHERE CITY_CODE =#ccode", conn);
comm.Parameters.AddWithValue("#ccode", ddlCity.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#ccode";
param.Value = ddlCity;
comm.Parameters.Add(param);
}
ddlSched.DataSource = dt;
ddlSched.DataTextField = "SCHEDULE";
ddlSched.DataValueField = "HOSPITAL_CODE";
ddlSched.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
When someone selects a value in the DropDownList and hits the button, it will display the lists of doctors available in the province, city and per particular schedule.
Check this sample. I have used SQLDatasource with SelectParameters for this example (you
can replace it with your own object datasource, custom binding etc.) SQLDataSource Select Parameters
The second dropdownlist automatically populates when the first dropdownlist is changed
On Button even I am just selecting the currently selected values of each dropdownlist (You can select your doctor list in the same way)
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Cascading DropDown.aspx.cs"
Inherits="Cascading_DropDown" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">
<title></title> </head> <body>
<form id="form1" runat="server">
<div>
<label>
Category:</label>
<asp:DropDownList ID="ddlCategories" runat="server" AppendDataBoundItems="True" AutoPostBack="True"
DataSourceID="sdsCategory" DataTextField="CategoryName" DataValueField="CategoryID"
OnSelectedIndexChanged="ddlCategories_SelectedIndexChanged">
<asp:ListItem Text="-Select-" Value="" />
</asp:DropDownList>
<br />
<label>
Products:</label>
<asp:DropDownList ID="ddlProducts" runat="server" DataSourceID="sdsProducts" DataTextField="ProductName"
DataValueField="ProductID">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Search Prodcut" OnClick="Button1_Click" />
<asp:Label ID="lblSelectedValues" runat="server"></asp:Label>
</div>
<asp:SqlDataSource ID="sdsCategory" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [CategoryID], [CategoryName] FROM [Categories] ORDER BY [CategoryName]">
</asp:SqlDataSource>
<asp:SqlDataSource ID="sdsProducts" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName] FROM [Alphabetical list of products] WHERE ([CategoryID] = #CategoryID)">
<SelectParameters>
<asp:ControlParameter ControlID="ddlCategories" Name="CategoryID" PropertyName="SelectedValue"
Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</form> </body> </html>
.CS
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ddlCategories_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCategories.SelectedValue == "")
{
ddlProducts.Items.Clear();
ddlProducts.SelectedIndex = -1;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
lblSelectedValues.Text = "You selected Category:" + ddlCategories.SelectedItem.Text + " & prodcut:" + ddlProducts.SelectedItem.Text;
}
You can drop a gridview on form like Abel said & on your button click event, fetch each drop down list selected value & execute your query & databaind your gridview like you are already doing with your drop down lists.
All you essentially need to do is to place the controls in the ASPX page declaratively:
<asp:DropDownList id="ddlSche" runat="server" />
You can calculate the results in the Page_Load using ddlSched.SelectedValue and similar methods.
Essentially, you use the button's onclick handler for this type of thing:. But since you already have a SelectedIndexChanged event, it seems that you're on the right track. It's fired when the user postbacks the page and the index was changed (or, in other words, the user selected something else than the current selection in the DropDownList).