The name '' does not exist in the current context - Sporadic - c#

I know this is a fairly common error, however the circumstances for me in this case are a little different.
Sometimes, I will not get this error, other times I will, which is not ideal.
Usually I change the inherit name and change the public partial class to the same and it works fine, but after a while I will receive the following.
Error 1 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 31 13 Branch(3)
Error 2 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 32 13 Branch(3)
Error 3 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 33 13 Branch(3)
Error 4 The name 'add_modules' does not exist in the current context all-modules.aspx.cs 34 13 Branch(3)
Error 5 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 42 13 Branch(3)
Error 6 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 43 13 Branch(3)
Error 7 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 44 13 Branch(3)
Below is my C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
public partial class all_modules: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
//Only allow admins, academic program managers and Senior University Managers to view page
helper.Authorised(1, 2, 3);
//get role_id of logged in user
int role_id;
role_id = Convert.ToInt32(Session["role_id"]);
//get id of logged in user
string user_id = Session["user_id"].ToString();
//if admin
if (role_id == 1 || role_id == 3) {
string query = "SELECT courses.course_name, staff_records.f_name, staff_records.l_name, modules.module_name, modules.module_tutor, modules.module_id FROM courses_vs_modules INNER JOIN modules ON courses_vs_modules.module_id = modules.module_id INNER JOIN staff_records ON modules.module_tutor = staff_records.user_id INNER JOIN courses ON courses_vs_modules.course_id = courses.course_id WHERE (courses.school IN (SELECT school_id FROM staff_records AS staff_records_1 WHERE (user_id = #user_id))) ORDER BY courses.course_name";
DataTable dt = GetData(query, user_id);
display_modules.DataSource = dt;
display_modules.DataBind();
display_modules.Visible = true;
add_modules.Visible = true;
}
//if senior uni manager
if (role_id == 2) {
string query = "SELECT courses.course_name, staff_records.f_name, staff_records.l_name, modules.module_name, modules.module_tutor, modules.module_id FROM courses_vs_modules INNER JOIN modules ON courses_vs_modules.module_id = modules.module_id INNER JOIN staff_records ON modules.module_tutor = staff_records.user_id INNER JOIN courses ON courses_vs_modules.course_id = courses.course_id ORDER BY courses.course_name";
DataTable dt = GetDataSen(query);
display_modules.DataSource = dt;
display_modules.DataBind();
display_modules.Visible = true;
}
}
private static DataTable GetData(string query, string user_id) {
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(query);
String constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
cmd.Parameters.AddWithValue("#user_id", user_id);
sda.Fill(dt);
return dt;
}
private static DataTable GetDataSen(string query) {
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(query);
String constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
}
And this is my ASP.net
<%# Page Title="All Modules" MasterPageFile="MasterPage.master" Language="C#" AutoEventWireup="true" CodeFile="~/all-modules.aspx.cs" Inherits="all_modules" %>
<asp:Content ContentPlaceHolderID="head" Runat="Server">
<script>
$(document).ready(function () {
//makes contains filter case insensitive
$.expr[":"].contains = $.expr.createPseudo(function (arg) {
return function (elem) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
//search has the user types
$('.search-box').keyup(function () {
var search_term = $(this).val();
if (search_term == "") {
//show all if nothing was entered
$('.project-link').removeClass('hide');
} else {
// hide all and then show only the search results
$('.project-link').addClass('hide');
$('.module-list *:contains("' + search_term + '")').closest('.project-link').removeClass('hide');
}
//check if any results were found
if ($('.project-link').not('.hide').length)
{
$('.no-results').addClass('hide');
} else {
$('.no-results').removeClass('hide');
}
});
});
</script>
</asp:Content>
<asp:Content ContentPlaceHolderID="menu" Runat="Server"></asp:Content>
<asp:Content ContentPlaceHolderID="main_content" Runat="Server">
<div class="row">
<div class="col-12">
<h1>All Modules</h1>
<h5 class="subheading">Search through a complete list of modules.</h5>
Add Modules
</div>
</div>
<div class="row">
<div class="col-12">
<div class="panel">
<h3>Search Modules:</h3>
<input type="text" class="search-box full-width" placeholder="Search via module name, code, course or lecturer" />
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="panel">
<asp:ListView ID="display_modules" runat="server" Visible="false">
<ItemTemplate>
<div class="project-link module-list">
<a href='<%# "module.aspx?module=" + Eval("module_id") %>'>
<p class="project-label"><%# Eval("course_name") %>
</p>
<asp:Label Text='
<%# Eval("module_id") + " - " %>' runat="server" CssClass="story-title" ID="Label1" />
<asp:Label Text='
<%# Eval("module_name") %>' runat="server" CssClass="story-title" ID="story_titleLabel" />
<span>
<p class="project-label"><%# Eval("f_name") + " " + Eval("l_name") %>
</p>
<div class="to-module"></div>
</a>
</div>
</ItemTemplate>
</asp:ListView>
<p class="hide no-results">No search results were found.</p>
</div>
</div>
</div>
</asp:Content>
Any idea why this might be happening? Any help would be greatly appreciated

Related

How to extract information from database?

I am trying to create a Login page and validating the incoming details against the database. But my code isn't able to cross check data from the database. Below is the output result I'm getting from the application:
Output
Following is the code I'm working on
Default.aspx Code:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master"AutoEventWireup="true" CodeFile="LogIn.aspx.cs" Inherits="LogIn" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
<!-- Login & Register -->
<section>
<div class="pageintro">
<div class="pageintro-bg">
<img src="images/bg-page_01.jpg" alt="About Us"/>
</div>
<div class="pageintro-body">
<h1 class="pageintro-title">Login</h1>
<nav class="pageintro-breadcumb">
<ul>
<li>
Home
</li>
<li>
Login
</li>
</ul>
</nav>
</div>
</div>
</section>
<!-- Login -->
<div class="col-lg-6 ">
<div class="au-form-body p-r-lg-15 p-r-xl-15">
<h2 class="au-form-title form-title-border">Login</h2>
<fieldset class="m-t-40">
<div class="form-group au-form require">
<label>Email address</label>
<asp:TextBox ID="txtemail" runat="server"></asp:TextBox>
</div>
<div class="form-group au-form require">
<label>Password</label>
<asp:TextBox ID="txtpwd" runat="server" TextMode="Password"></asp:TextBox>
</div>
<div class="form-group au-form">
<asp:Button ID="loginbtn" runat="server" Text="Log In" OnClick="Button1_Click" />
<asp:Label ID="loginmessage" runat="server"></asp:Label>
<asp:Button ID="logoutbtn" runat="server" OnClick="Button2_Click" Text="Log Out" Visible="False" />
<div class="form-forgot w-100 m-t-10">
Lost your password?
</div>
</div>
</fieldset>
</div>
</div>
<!-- End Login -->
Default.aspx.cs Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class LogIn : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=TEAFAMILY;Initial Catalog=Bolsen;Integrated Security=True; MultipleActiveResultSets=true;");
sqlCon.Open();
Type cstype = this.GetType();
SqlCommand cmd;
SqlDataReader rdr;
String strSql1 = "SELECT * FROM Customers ";
cmd = new SqlCommand(strSql1, sqlCon);
rdr = cmd.ExecuteReader();
while (rdr.Read() == true)
{
if (txtemail.Text == (string)rdr["cEmail"] &&
txtpwd.Text == (string)rdr["cPassword"])
{
Session["sFlag"] = "T"; // sFlag = "T" means user has logged in
Session["sName"] = rdr["Firstname"];
Session["sEmail"] = rdr["cEmail"];
Session["sAddress"] = rdr["cCompanyAddress"];
Session["sEmail"] = rdr["cEmail"];
logoutbtn.Visible = true;
sqlCon.Close();
Response.Redirect("Default.aspx");
} //end of if
} //end of while loop
// userid and password not matched, hence login unsuccessful
Session["sFlag"] = "F";
Session["sName"] = "";
Session["sUserId"] = "";
loginmessage.Text = "Error in login - Please login again ";
sqlCon.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
logoutbtn.Visible = false;
Session["sFlag"] = "L"; // L for logout
Session["sName"] = "";
Session["sUserId"] = "";
Session["sOrderNo"] = "";
txtemail.Text = "";
txtpwd.Text = "";
Response.Redirect("Default.aspx");
}
}
Would someone point out what's wrong with the code?
No need to fetch all the records from the database just to check a single result. Change your Button1_Click event code to this:
protected void Button1_Click(object sender, EventArgs e)
{
string username = txtemail.Text;
string password = txtpwd.Text;
using (SqlConnection sqlCon = new SqlConnection(#"Data Source=TEAFAMILY;Initial Catalog=Bolsen;Integrated Security=True; MultipleActiveResultSets=true;"))
{
string query = "SELECT Top(1) * FROM Customers WHERE cEmail = #Username and cPassword = #Password";
SqlCommand cmd = new SqlCommand(query, sqlCon);
cmd.Parameters.AddWithValue("#Username", username);
cmd.Parameters.AddWithValue("#Password", password);
sqlCon.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
Session["sFlag"] = "T"; // sFlag = "T" means user has logged in
Session["sName"] = rdr["Firstname"];
Session["sEmail"] = rdr["cEmail"];
Session["sAddress"] = rdr["cCompanyAddress"];
Session["sEmail"] = rdr["cEmail"];
logoutbtn.Visible = true;
sqlCon.Close();
Response.Redirect("Default.aspx");
}
else
{
Session["sFlag"] = "F";
Session["sName"] = "";
Session["sUserId"] = "";
loginmessage.Text = "Error in login - Please login again ";
}
}
}

How to retrieving & display data from multiple tables under the same heading?

I am making an Employee Roster Scheduler.
Currently, I'm trying to use a repeater to display the current shifts in a calendar format.
Below is my current output:
As you can see, there are 2 shifts on Saturday. Does anyone know how I can place these two shifts under one header, so Saturday 03 June 2017 only appears once, rather than twice?
Below you can find my code:
HTML:
<div class="col-lg-12">
<asp:Repeater ID="repSubscription" runat="server" OnItemDataBound="repSubscription_ItemDataBound">
<ItemTemplate>
<div class="col-lg-2">
<div class="panel panel-default">
<div class="panel-heading" style="background-color: #3A6EA5; color: white">
<h4 class="panel-title">
<%# Eval("Start_Time", "{0:dddd, dd MMMM yyyy}") %>
</h4>
</div>
<!--panel-heading-->
<div class="panel-body">
<asp:Repeater ID="repShift" runat="server">
<ItemTemplate>
<b><%# Eval("Job_Title") %></b>
</ItemTemplate>
</asp:Repeater>
</br>
<asp:Repeater ID="repEmp" runat="server">
<ItemTemplate>
<%# Eval("Employee_Name") %>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:Repeater ID="repTimes" runat="server">
<ItemTemplate>
<%# Eval("Start_Time", "{00:HH:MM}") %> - <%# Eval("End_Time" , "{00:HH:MM}") %>
</ItemTemplate>
</asp:Repeater>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
this.bindRepeater();
}
private void bindRepeater()
{
conn = new SqlConnection(connectionString);
conn.Open();
comm = new SqlCommand("SELECT DISTINCT Start_Date, End_Date FROM My_Subscription WHERE Subscription_Id = 1", conn);
SqlDataReader reader1 = comm.ExecuteReader();
while (reader1.Read())
{
startDate = Convert.ToDateTime(reader1["Start_Date"]);
endDate = Convert.ToDateTime(reader1["End_Date"]);
//lblError.Text += startDate.ToString() + "<br/>" + endDate.ToString();
}
conn.Close();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT Start_Time, Emp_ID, Job_ID, Emp_Sch_Id FROM My_Employee_Schedule WHERE Start_Time BETWEEN #startReportDate AND #endReportDate", con))
{
cmd.Parameters.AddWithValue("#startReportDate", startDate);
cmd.Parameters.AddWithValue("#endReportDate", endDate);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
repSubscription.DataSource = dt;
repSubscription.DataBind();
}
}
}
}
protected void repSubscription_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
conn = new SqlConnection(connectionString);
conn.Open();
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater repBusiness = (Repeater)(e.Item.FindControl("repShift"));
SqlCommand cmd = new SqlCommand("SELECT Job_Title FROM My_Job_Type WHERE Job_Type_Id=#Job_Type_Id");
string Group_Id = DataBinder.Eval(e.Item.DataItem, "Job_ID").ToString();
cmd.Parameters.AddWithValue("#Job_Type_Id", Group_Id);
//Need to assign the Data in datatable
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
repBusiness.DataSource = dt;
repBusiness.DataBind();
}
conn.Close();
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater repTimes = (Repeater)(e.Item.FindControl("repTimes"));
SqlCommand cmd = new SqlCommand("SELECT Start_Time, End_Time FROM My_Employee_Schedule WHERE Emp_Sch_Id=#EmpSchId");
string Group_Id = DataBinder.Eval(e.Item.DataItem, "Emp_Sch_Id").ToString();
cmd.Parameters.AddWithValue("#EmpSchId", Group_Id);
//Need to assign the Data in datatable
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
repTimes.DataSource = dt;
repTimes.DataBind();
}
conn.Open();
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater repEmp = (Repeater)(e.Item.FindControl("repEmp"));
SqlCommand cmd = new SqlCommand("SELECT Employee_Name FROM My_Employee WHERE Employee_Id=#EmpId");
string Group_Id = DataBinder.Eval(e.Item.DataItem, "Emp_ID").ToString();
cmd.Parameters.AddWithValue("#EmpId", Group_Id);
//Need to assign the Data in datatable
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
repEmp.DataSource = dt;
repEmp.DataBind();
}
conn.Close();
}
, then I am happy to post it.
Thanks a lot for any help in advance!

Attaching an existing but modified entity to the context (Drop-down list from Database)

Experts,
Drop-down list is picking data from database and saving against the same column upon opening the web page and save the data, where saving is happening in another instead of same name,
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div class="form">
<p>
<asp:Label ID="Label1" runat="server" Text="Place Name" AssociatedControlID="txtName"></asp:Label>
<asp:DropDownList ID="txtName" runat="server" >
</asp:DropDownList>
</p>
<p>
<asp:Label ID="Label2" runat="server" Text="Address" AssociatedControlID="txtAddress"></asp:Label>
<asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>
</p>
<p>
<asp:HiddenField ID="hdnLocation" runat="server" />
</p>
<p>
<asp:Button ID="btnSubmit" runat="server" Text="Save" OnClick="btnSubmit_Click" />
</p>
<p id="message"></p>
</div>
</form>
<script type="text/javascript">
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
else { $("#message").html("Geolocation is not supported by this browser."); }
function showPosition(position) {
var latlondata = position.coords.latitude + "," + position.coords.longitude;
var latlon = "Latitude" + position.coords.latitude + "," + "Longitude" + position.coords.longitude;
$("#message").html(latlon);
$("[id*=hdnLocation]").val(position.coords.longitude + " " + position.coords.latitude);
}
function showError(error) {
if (error.code == 1) {
$("#message").html("User denied the request for Geolocation.");
}
else if (error.code == 2) {
$("#message").html("Location information is unavailable.");
}
else if (error.code == 3) {
$("#message").html("The request to get user location timed out.");
}
else {
$("#message").html("An unknown error occurred.");
}
}
</script>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Data.Entity.Spatial;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string query = "SELECT PlaceID, Name,Address FROM Placeinfo";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ListItem item = new ListItem();
item.Text = sdr["Name"].ToString();
txtName.Items.Add(item);
txtName.ClearSelection();
}
}
con.Close();
}
}
}
}
public List<PlaceInfo> GetMyPlaces()
{
return new SampleDBEntities().PlaceInfoes.ToList();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
PlaceInfo placeToEdit = Context.placeinfoes.Find(Convert.ToInt32(txtName.DataValueField));
using (var context = new SampleDBEntities())
{
PlaceInfo placeToUpdate = context.PlaceInfoes.Find(Convert.ToInt32(txtName.DataValueField));
placeToUpdate.Name = txtName.Text;
placeToUpdate.Address = txtAddress.Text;
placeToUpdate.Geolocation = DbGeography.FromText("POINT( " + hdnLocation.Value + ")");
context.Entry(placeToUpdate).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
}
}
}
databaseDATABASE DISPLAY
In order to update an item in a database, we first need to make sure we'll know which one we need to reference.
First, with the creation of your DropDownList, we'll want to hide the ID of the "PlaceInfo" we are displaying. This will create the need for a "SelectMethod", and a few other adjustments:
<asp:DropDownList ID="txtName" runat="server" ItemType="PlaceInfo" DataValueField="PlaceId" DataTextField="Name" SelectMethod="GetMyPlaces"></asp:DropDownList>
The DataTextField property is the one which will display in the actual DropDown, and the DataValueField is a hidden property which we will use to reference the ID so we can call that row later.
The SelectMethod (I have as: GetMyPlaces) is the method we use to populate the DropDownList. Please excuse the brevity, as you can do this a number of ways, but essentially you want to return a list of PlaceInfos:
public List<PlaceInfo> GetMyPlaces()
{
return new SampleDbEntities().PlaceInfoes.ToList();
}
Finally - in the btnSubmit_Click method, you want to grab the row we're going to edit by using the hidden Value field from the dropdown :
PlaceInfo placeToEdit = Context.PlaceInfoes.Find(Convert.ToInt32(txtName.Value))
Assign it the new values, and tell entity framework this model is now modified:
using (var context = new SampleDBEntities())
{
PlaceInfo placeToUpdate = context.PlaceInfoes.Find(Convert.ToInt32(txtName.Value));
placeToUpdate.Name = txtName.Text;
placeToUpdate.Address = txtAddress.Text;
placeToUpdate.Geolocation = DbGeography.FromText("POINT( "+hdnLocation.Value+")");
context.Entry(placeToUpdate).State = EntityState.Modified;
context.SaveChanges();
}
Save the changes to your context and you should be good to go.

Creating dynamic DIV in asp .net c#

I am creating DIVs dynamically which will fetch data from my sql table(from each row) and will show it in DIVs. What problem I am facing is, it only shows the last row of my sql table in a div form
Here is the html
<div ID = "containerDiv" class="container" runat = "server">
<div ID = "columnDiv" class="col-md-3 col-sm-4" runat = "server">
<div ID = "textDiv" class="text" runat="server">
</div>
</div>
</div>
and here is the cs code
static int count = 0;
protected void Page_Load(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM tblProducts"))
{
cmd.Connection = con;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
columnDiv.ID = "columnDiv" + count;
textDiv.ID = "textDiv" + count;
string name = rdr["prod_name"].ToString();
string price = rdr["prod_price"].ToString();
textDiv.InnerHtml = name + " " + price;
columnDiv.Controls.Add(textDiv);
containerDiv.Controls.Add(columnDiv);
count++;
}
}
}
}
Try using a Repeater, like this (here's the MSDN):
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div ID="containerDiv" class="container" runat = "server">
<div ID="columnDiv" class="col-md-3 col-sm-4" runat = "server">
<div ID="textDiv" class="text" runat="server">
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
And supply a DataSource in the code behind on the server, and add '<%# Eval("ColumnName") %>' expressions in the markup where appropriate.
The standard approach is to use a GridView:
https://msdn.microsoft.com/en-us/library/aa479342.aspx

CascadingDropDown Error

I am trying to get my cascading comboboxes to work, but am getting a [Method error 500]. Any ideas? I've searched online, the code should work....Thanks in advance for your help!
ADDSTORY.ASPX:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="addstory.aspx.cs" Inherits="addstory" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
...
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ScriptManager1" runat="server" />
...
<td class="style3">
<asp:DropDownList ID="selectproject" runat="server" Width="225"></asp:DropDownList>
<asp:CascadingDropDown ID="ccd1" runat="server"
ServicePath="~/dropdown.asmx?company=<%=co_id %>" ServiceMethod="GetProjects"
TargetControlID="selectproject" Category="Project"
PromptText="Select Project" />
</td>
</tr>
<tr>
<td class="style3"></td>
<td width = "150" class="style3">Iteration:</td>
<td class="style3">
<asp:DropDownList ID="selectiteration" runat="server" Width="225"></asp:DropDownList>
<asp:CascadingDropDown ID="ccd2" runat="server"
ServicePath="~/dropdown.asmx?company=<%=co_id %>" ServiceMethod="GetIterations"
TargetControlID="selectiteration" Category="Iteration"
PromptText="Select Iteration" />
</td>
</tr>
DROPDOWN.ASMX:
using System.Web.Script.Services;
using AjaxControlToolkit;
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data.SqlClient;
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService()]
public class dropdown : System.Web.Services.WebService
{
private string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
}
[WebMethod]
public CascadingDropDownNameValue[] GetProjects(string knownCategoryValues, string category)
{
string co_id = this.Context.Request.QueryString["company"].ToString();
SqlConnection conn = new SqlConnection(GetConnectionString());
conn.Open();
SqlCommand comm = new SqlCommand("Select ProjectName, ProjectID FROM Project WHERE CompanyID = '" + co_id + "'", conn);
SqlDataReader dr = comm.ExecuteReader();
List<CascadingDropDownNameValue> l = new List<CascadingDropDownNameValue>();
while (dr.Read())
{
l.Add(new CascadingDropDownNameValue(dr["ProjectName"].ToString(), dr["ProjectID"].ToString()));
}
conn.Close();
return l.ToArray();
}
[WebMethod]
public CascadingDropDownNameValue[] GetIterations(string knownCategoryValues, string category)
{
int ProjectID;
StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
if (!kv.ContainsKey("Project") || !Int32.TryParse(kv["Project"], out ProjectID))
{
throw new ArgumentException("Couldn't find project.");
};
SqlConnection conn = new SqlConnection(GetConnectionString());
conn.Open();
SqlCommand comm = new SqlCommand("SELECT Select CONVERT(VARCHAR(10), StartDate, 103) + ' - ' + CONVERT(VARCHAR(10), EndDate, 103) AS Iteration, ProjectIterationID FROM Iterations WHERE ProjectID=#ProjectID", conn);
comm.Parameters.AddWithValue("#ProjectID", ProjectID);
SqlDataReader dr = comm.ExecuteReader();
List<CascadingDropDownNameValue> l = new List<CascadingDropDownNameValue>();
while (dr.Read())
{
l.Add(new CascadingDropDownNameValue(dr["Iteration"].ToString(), dr["ProjectIterationID"].ToString()));
}
conn.Close();
return l.ToArray();
}
}
I see you have already flagged your service as ScriptService, however you forgot to flag individual methods with the [ScriptMethod] attribute.
Also in the service path property of your cascading drop down controls I would take out the ~ and just use /dropdown.asmx

Categories