I have a table of assignments. I want to get the total number of points earned by an enrolled student and the total number of points possible for that student. I have an asp class that calculates the letter grade and updates the enrollment record in the database with the letter grade. I keep getting the error Invalid attempt to read when no data is present. I have pointed out the line the error occurs on.
This is my assignments table:
As you can see, there are plenty of assignments for enrollmentId 69. I use the following stored procedure to get the assignments:
ALTER PROCEDURE [dbo].[GetScores]
#enrollmentId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT sum(pointsEarned) AS totalEarned, sum(pointsPossible) AS totalPossible, enrollmentId
FROM Assignments
WHERE enrollmentId = #enrollmentId
GROUP BY pointsEarned, pointsPossible, enrollmentId
END
This is the code-behind file:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
PopulateSemesterList();
}
private void PopulateSemesterList()
{
string connstring;
connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("dbo.GetSemesters", conn);
conn.Open();
DDSemesters.DataSource = cmd.ExecuteReader();
DDSemesters.DataTextField = "semesterName";
DDSemesters.DataValueField = "semesterId";
this.DataBind();
conn.Close();
conn.Dispose();
DDSemesters.Items.Insert(0, new ListItem("Select Semester", "0"));
DDSemesters.SelectedIndex = 0;
}
protected void DDSemesters_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList DDSemesters = sender as DropDownList;
int selectedSemester = Convert.ToInt32(DDSemesters.SelectedItem.Value);
string connstring;
connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("dbo.GetCourses", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#semesterId", selectedSemester));
conn.Open();
DDCourses.DataSource = cmd.ExecuteReader();
DDCourses.DataTextField = "courseName";
DDCourses.DataValueField = "courseId";
this.DataBind();
conn.Close();
conn.Dispose();
DDCourses.Items.Insert(0, new ListItem("Select Course", "0"));
DDCourses.SelectedIndex = 0;
DDCourses.Visible = true;
CoursesLbl.Visible = true;
}
protected void DDCourses_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList DDCourses = sender as DropDownList;
int selectedCourse = Convert.ToInt32(DDCourses.SelectedItem.Value);
string connstring;
connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("dbo.CourseEnrollment", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#courseId", selectedCourse));
conn.Open();
DDStudents.DataSource = cmd.ExecuteReader();
DDStudents.DataTextField = "fullName";
DDStudents.DataValueField = "enrollmentId";
this.DataBind();
conn.Close();
conn.Dispose();
DDStudents.Items.Insert(0, new ListItem("Select Student", "0"));
DDStudents.SelectedIndex = 0;
DDStudents.Visible = true;
StudentLbl.Visible = true;
}
protected void DDStudents_SelectedIndexChanged(object sender, EventArgs e)
{
assignmentInfoDiv.Visible = true;
studentName.Text = DDStudents.SelectedItem.Text;
}
protected void SaveScore_Click(object sender, EventArgs e)
{
Grades studentGrade = new Grades();
studentGrade.courseId = Convert.ToInt32(DDCourses.SelectedItem.Value);
studentGrade.enrollmentId = Convert.ToInt32(DDStudents.SelectedItem.Value);
studentGrade.assignmentName = AssignmentList.SelectedItem.Text;
studentGrade.pointsPossible = Convert.ToInt32(possibleTxt.Text);
studentGrade.pointsEarned = Convert.ToInt32(earnedTxt.Text);
if (studentGrade.alreadyExistsg())
{
AssignmentError.Text = "This student has already submitted " + studentGrade.assignmentName + " for this course.";
}
else
{
if (studentGrade.saveScore())
{
Response.Redirect("StudentList.aspx");
}
else
{
AssignmentError.Text = "Oops! Something went wrong...";
}
}
}
This is Grades.cs class:
public void calculate()
{
string letterGrade;
string connstring;
connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("dbo.GetScores", conn);
cmd.Parameters.Add(new SqlParameter("#enrollmentId", courseId));
cmd.CommandType = System.Data.CommandType.StoredProcedure;
using (conn)
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
Error Here----> double totalEarned = Convert.ToDouble(reader["totalEarned"]);
double totalPossible = Convert.ToDouble(reader["totalPossible"]);
double score = Math.Round(totalEarned / totalPossible, 2) * 100;
if (score >= 90)
{
letterGrade = "A";
}
else if (score < 90 && score >= 80)
{
letterGrade = "B";
}
else if (score < 80 && score >= 70)
{
letterGrade = "C";
}
else if (score < 70 && score >= 60)
{
letterGrade = "D";
}
else
{
letterGrade = "F";
}
update(letterGrade);
conn.Close();
conn.Dispose();
}
}
public Boolean saveScore()
{
string connstring;
connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand add = new SqlCommand("dbo.AddScore", conn);
add.Parameters.Add("#enrollmentId", System.Data.SqlDbType.Int);
add.Parameters["#enrollmentId"].Value = enrollmentId;
add.Parameters.Add("#assignmentName", System.Data.SqlDbType.Char);
add.Parameters["#assignmentName"].Value = assignmentName;
add.Parameters.Add("#pointsPossible", System.Data.SqlDbType.Int);
add.Parameters["#pointsPossible"].Value = pointsPossible;
add.Parameters.Add("#pointsEarned", System.Data.SqlDbType.Int);
add.Parameters["#pointsEarned"].Value = pointsEarned;
add.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
int outputval = add.ExecuteNonQuery();
conn.Close();
conn.Dispose();
if (outputval == -1)
{
calculate();
return true;
}
else
{
return false;
}
}
private void update(string letterGrade)
{
string connstring;
connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("dbo.UpdateGrade", conn);
cmd.Parameters.Add(new SqlParameter("#enrollmentId", enrollmentId));
cmd.Parameters.Add(new SqlParameter("#letterGrade", letterGrade));
cmd.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
Here is my ASP:
<asp:Label ID="Label1" runat="server" Text="Select Semester"></asp:Label><br />
<asp:DropDownList ID="DDSemesters" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DDSemesters_SelectedIndexChanged" DataTextField="semesterName" DataValueField="semesterId"></asp:DropDownList><br />
<asp:Label ID="CoursesLbl" runat="server" Text="Select Course" Visible="false"></asp:Label><br />
<asp:DropDownList visible="false" ID="DDCourses" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DDCourses_SelectedIndexChanged" DataTextField="courseName" DataValueField="courseId"></asp:DropDownList><br />
<asp:Label ID="StudentLbl" runat="server" Text="Select Student" Visible="false"></asp:Label><br />
<asp:DropDownList visible="false" ID="DDStudents" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DDStudents_SelectedIndexChanged" DataTextField="fullName" DataValueField="enrollmentId"></asp:DropDownList><br />
<div id="assignmentInfoDiv" runat="server" visible="false" style="margin-top: 50px;">
<asp:Label ID="studentName" runat="server" Text="Student Name" ></asp:Label>
<asp:Label ID="AssignmentLbl" runat="server" Text="Assignment"></asp:Label><br />
<asp:DropDownList ID="AssignmentList" runat="server">
<asp:ListItem Text="Assignment 1"></asp:ListItem>
<asp:ListItem Text="Assignment 2"></asp:ListItem>
<asp:ListItem Text="Assignment 3"></asp:ListItem>
<asp:ListItem Text="Assignment 4"></asp:ListItem>
<asp:ListItem Text="Assignment 5"></asp:ListItem>
<asp:ListItem Text="Assignment 6"></asp:ListItem>
<asp:ListItem Text="Assignment 7"></asp:ListItem>
<asp:ListItem Text="Assignment 8"></asp:ListItem>
<asp:ListItem Text="Assignment 9"></asp:ListItem>
<asp:ListItem Text="Assignment 10"></asp:ListItem>
<asp:ListItem Text="Quiz 1"></asp:ListItem>
<asp:ListItem Text="Quiz 2"></asp:ListItem>
<asp:ListItem Text="Midterm Project"></asp:ListItem>
<asp:ListItem Text="Final Project"></asp:ListItem>
</asp:DropDownList>
<asp:Label ID="earnedLbl" runat="server" Text="Points Earned:"></asp:Label>
<asp:TextBox ID="earnedTxt" runat="server"></asp:TextBox>
<asp:Label ID="possibleLbl" runat="server" Text="Points Possible:"></asp:Label>
<asp:TextBox ID="possibleTxt" runat="server"></asp:TextBox>
<asp:Button ID="SaveScore" runat="server" Text="Save" OnClick="SaveScore_Click" />
<asp:Label ID="AssignmentError" runat="server"></asp:Label>
</div>
What am I doing wrong?
Related
The list box in the below updatePanel triggers the postback only once, for example if I select pre-Purchase on ddlroot it loads the appropriate data on ddlchild, but if I select post-order again it doesn't load the data needed.
<asp:UpdatePanel ID="UpdatePanel5" ChildrenAsTriggers="true" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlroot" EventName="TextChanged" />
<asp:AsyncPostBackTrigger ControlID="ddlchild" EventName="Textchanged" />
</Triggers>
<ContentTemplate>
<table>
<tr>
<td>
<asp:ListBox ID="ddlroot" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlroot_SelectedIndexChanged">
<asp:ListItem Value="pre-purchase" Text="Pre-Purchase"></asp:ListItem>
<asp:ListItem Value="post-purchase" Text="Post-Purchase"></asp:ListItem>
</asp:ListBox>
</td>
<td>
<asp:ListBox ID="ddlchild" runat="server"></asp:ListBox>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
Below would be the server side code where based on the ddlroot selection the data will be fetched from MySql database,
protected void ddlroot_SelectedIndexChanged(object sender, EventArgs e)
{
ddlchild.Items.Clear();
string MyConString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
if (ddlroot.SelectedValue == "pre-purchase")
{
using (MySqlConnection conn = new MySqlConnection(MyConString))
{
using (MySqlCommand cmd1 = new MySqlCommand())
{
cmd1.CommandText = "select distinct(prePurchase) from prepurchase WHERE prePurchase IS NOT NULL";
cmd1.Connection = conn;
conn.Open();
using (MySqlDataReader sdr1 = cmd1.ExecuteReader())
{
while (sdr1.Read())
{
ListItem item1 = new ListItem();
item1.Text = sdr1["prePurchase"].ToString();
item1.Value = sdr1["prePurchase"].ToString();
ddlchild.Items.Add(item1);
}
}
conn.Close();
}
}
}
else if(ddlroot.SelectedValue == "post-purchase")
{
using (MySqlConnection conn = new MySqlConnection(MyConString))
{
using (MySqlCommand cmd1 = new MySqlCommand())
{
cmd1.CommandText = "select distinct(postPurchase) from prepurchase WHERE postPurchase IS NOT NULL";
cmd1.Connection = conn;
conn.Open();
using (MySqlDataReader sdr1 = cmd1.ExecuteReader())
{
while (sdr1.Read())
{
ListItem item1 = new ListItem();
item1.Text = sdr1["postPurchase"].ToString();
item1.Value = sdr1["postPurchase"].ToString();
ddlchild.Items.Add(item1);
}
}
conn.Close();
}
}
}
//UpdatePanel5.Update();
}
How can I fix this?
I have 3 dropdownlist: select year, select make, select model. Upon select model the results should appear in a gridview. My tables are:
Makes with [(pk)MakeID, MakeName]; Models with [(pk)ModelID, Make_ID, ModelYear, ModelName]; and Wipers with [(pk)WiperID, Model_ID, Description, Emplacement, Price]. When I step through debug, I see 6 counts of records found, but I do not see it in gridview
I've looked at these for help, but no answers
ASP.net DropDownList populates GridView
Binding gridview with arraylist asp.net/c#
My Default.aspx
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="wrapper" align="center">
<asp:DropDownList ID="ddlYear" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="Year_Changed">
</asp:DropDownList>
<asp:DropDownList ID="ddlMake" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="Make_Changed">
</asp:DropDownList>
<asp:DropDownList ID="ddlModel" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="Get_Wipers_By_Model">
</asp:DropDownList>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:GridView ID="grdWiperList" runat="server">
</asp:GridView>
</form>
My Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Year drop down list is populated on page load
string query = "SELECT DISTINCT ModelYear FROM Models";
string connectionString = ConfigurationManager.ConnectionStrings["wiperConnectionString"].ToString();
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = conn;
conn.Open();
ddlYear.DataSource = cmd.ExecuteReader();
ddlYear.DataValueField = "ModelYear";
ddlYear.DataBind();
conn.Close();
}
}
ddlYear.Items.Insert(0, new ListItem("Select Year", "0"));
ddlMake.Enabled = false;
ddlModel.Enabled = false;
ddlMake.Items.Insert(0, new ListItem("Select Make", "0"));
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
}
}
private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
string connectionString = ConfigurationManager.ConnectionStrings["wiperConnectionString"].ToString();
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = conn;
conn.Open();
ddl.DataSource = cmd.ExecuteReader();
ddl.DataTextField = text;
ddl.DataValueField = value;
ddl.DataBind();
conn.Close();
}
}
ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}
protected void Year_Changed(object sender, EventArgs e)
{
//the Makes drop down list is populated on OnSelectedIndexChange event of the Year_Changed event
ddlMake.Enabled = false;
ddlModel.Enabled = false;
ddlMake.Items.Clear();
ddlModel.Items.Clear();
ddlMake.Items.Insert(0, new ListItem("Select Make", "0"));
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
int yearId = int.Parse(ddlYear.SelectedItem.Value);
if (yearId > 0)
{
string query = string.Format("SELECT DISTINCT MakeID, MakeName FROM Makes JOIN Models ON Make_ID = MakeID WHERE ModelYear = {0}", yearId);
BindDropDownList(ddlMake, query, "MakeName", "MakeID", "Select Make");
ddlMake.Enabled = true;
}
}
protected void Make_Changed(object sender, EventArgs e)
{
ddlModel.Enabled = false;
ddlModel.Items.Clear();
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
int yearID = int.Parse(ddlYear.SelectedItem.Value);
int makeId = int.Parse(ddlMake.SelectedItem.Value);
if (makeId > 0)
{
string query = string.Format("SELECT ModelID, ModelName FROM Models WHERE ModelYear = {0} AND Make_ID = {1}", yearID, makeId);
BindDropDownList(ddlModel, query, "ModelName", "ModelID", "Select Model");
ddlModel.Enabled = true;
}
}
protected void Get_Wipers_By_Model(object sender, EventArgs e)
{
grdWiperList.DataSource = Connection.GetWipersByModel
(!IsPostBack ? "%" : ddlModel.SelectedValue);
grdWiperList.DataBind();
}
}
My Connection.cs
public static ArrayList GetWipersByModel(string modelType)
{
ArrayList listResults = new ArrayList();
string query = string.Format
("SELECT * FROM Wipers WHERE Model_ID LIKE '{0}'", modelType);
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = query;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int wiperID = reader.GetInt32(0);
int model_id = reader.GetInt32(1);
string description = reader.GetString(2);
string itemNo = reader.GetString(3);
string emplacement = reader.GetString(4);
decimal price = reader.GetDecimal(5);
Wipers wipers = new Wipers(wiperID, model_id, description, itemNo, emplacement, price);
listResults.Add(wipers);
}
}
finally
{
conn.Close();
}
return listResults;
}
I think this because the updatePanel control try to add trigger between UpdatePanel control and DropDownList Control
i am using sql query to fetch the data from one dropdown list and want to change the second dropdown list by filter data i mean i am selecting the 1st dropdown list and the 2nd drop downlist show all the customer but i want the specific customer by cardcode when i select cardcode.
kindly help, thanks in advance
here is my 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;
using System.Data.SqlClient;
namespace StackOver
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadOptions();
}
}
protected void LoadOptions()
{
DataTable CardCode = new DataTable();
string id, name, newName, name2;
SqlConnection connection = new SqlConnection("Data Source=adfsadf;Initial Catalog=TestDatabse;Persist Security Info=True;User ID=asd;Password=asdf");
using (connection)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT T1.CardCode , T1.CardName, T2.OpprId,T1.CntctPrsn, T2.CprCode,T2.MaxSumLoc FROM OCRD T1 left join OOPR T2 on T1.CardCode=T2.CardCode" , connection);
adapter.Fill(CardCode);
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
id = CardCode.Rows[i]["CardCode"].ToString();
name = CardCode.Rows[i]["CardName"].ToString();
newName = id + " ---- " + name;
//name2 = id;
DropDownList1.Items.Add(new ListItem(newName, id));
name2 = CardCode.Rows[i]["CntctPrsn"].ToString();
DropDownList2.Items.Add(new ListItem(name2, name2));
}
}
//adapter.Fill(CardCode);
//DropDownList1.DataValueField = "CardCode";
//DropDownList1.DataTextField = "CardCode";
//DropDownList1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = DropDownList1.SelectedItem.Value;
SqlConnection connection = new SqlConnection("Data Source=mydtasrc;Initial Catalog=TestDatabs;Persist Security Info=True;User ID=asf;Password=asdfgh");
using (connection)
{
// SqlCommand theCommand = new SqlCommand("SELECT CardCode, CardName, OpprId, CprCode,MaxSumLoc FROM OOPR WHERE CardCode = #CardCode", connection);
SqlCommand theCommand = new SqlCommand("SELECT T1.CardCode , T1.CardName, T2.OpprId, T1.CntctPrsn,T2.CprCode FROM OCRD T1 left join OOPR T2 on T1.CardCode=T2.CardCode where T1.CardCode=#CardCode", connection);
connection.Open();
theCommand.Parameters.AddWithValue("#CardCode", selected);
theCommand.CommandType = CommandType.Text;
SqlDataReader theReader = theCommand.ExecuteReader();
if (theReader.Read())
{
// Get the first row
// theReader.Read();
// Set the text box values
this.TextBox1.Text = theReader["CardCode"].ToString();
this.TextBox2.Text = theReader["CardName"].ToString();
this.TextBox5.Text = theReader["CprCode"].ToString();
this.TextBox3.Text = theReader["OpprId"].ToString();
this.DropDownList2.Text = theReader["CntctPrsn"].ToString();
// this.TextBox3 = reader.IsDBNull(TextBox3Index) ? null : reader.GetInt32(TextBox3Index)
// GenreID = reader.IsDBNull(genreIDIndex) ? null : reader.GetInt32(genreIDIndex)
// this.TextBox4.Text = theReader.GetString(3);
// TextBox5.Text = theReader.GetString(4);
// TextBox6.Text = theReader.GetString(5);
// TextBox7.Text = theReader.GetString(6);
}
connection.Close();
}
}
public object TextBox3Index { get; set; }
// protected void Button1_Click(object sender, EventArgs e)
// {
// SqlConnection connection = new SqlConnection();
// connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["TestDataBaseConnectionString2"].ConnectionString;
// connection.Open();
// SqlCommand cmd = new SqlCommand();
// cmd.CommandText = "select * from OOPR";
// cmd.Connection = connection;
// SqlDataAdapter da = new SqlDataAdapter();
// da.SelectCommand = cmd;
// DataSet ds = new DataSet();
// da.Fill(ds, " OOPR");
// SqlCommandBuilder cb = new SqlCommandBuilder(da);
// DataRow drow = ds.Tables["OOPR"].NewRow();
// drow["CardCode"] = TextBox1.Text;
// drow["CardName"] = TextBox2.Text;
// drow["OpprId"] = TextBox3.Text;
// drow["CprCode"] = TextBox4.Text;
// drow["MaxSumLoc"] = TextBox5.Text;
// ds.Tables["OOPR"].Rows.Add(drow);
// da.Update(ds, " OOPR ");
// string script = #"<script language=""javascript"">
// alert('Information have been Saved Successfully.......!!!!!.');
// </script>;";
// Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
// }
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
using (connection)
{
// connection.Open();
SqlCommand insert = new SqlCommand("Insert into OOPR(CardCode, CardName, OpprId, CprCode,MaxSumLoc) values (#TextBox1,#TextBox2,#TextBox3,#TextBox4,#TextBox5 )", connection); //('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DropDownList1.Text + "','" + TextBox4.Text + "')", connection);
insert.Parameters.AddWithValue("#TextBox1", TextBox1.Text);
insert.Parameters.AddWithValue("#TextBox2", TextBox2.Text);
insert.Parameters.AddWithValue("#TextBox3", TextBox3.Text);
insert.Parameters.AddWithValue("#TextBox4", TextBox4.Text);
insert.Parameters.AddWithValue("#TextBox5", TextBox4.Text);
connection.Open();
// connection.CommandType=CommandType.Text;
// connection.commandType=CommandType.Text;
// try
// {
insert.ExecuteNonQuery();
connection.Close();
// }
//catch
//{
// TextBox5.Text = "Error when saving on database";
// connection.Close();
//}
//TextBox1.Text="";
//TextBox2.Text = "";
//TextBox3.Text = "";
//TextBox4.Text="";
}
}
protected void Button2_Click(object sender, EventArgs e)
{
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "Close", "window.close()", true);
// this.close();
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
and here is the apsx code
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="StackOver._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server"
onselectedindexchanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
</h2>
<br />
<p>
Business Partner Code :
<asp:TextBox ID="TextBox1" runat="server" Width="192px" ></asp:TextBox>
</p>
<p>
Business Partner Name :
<asp:TextBox ID="TextBox2" runat="server" Width="192px" ></asp:TextBox>
</p>
<p>
Opportunity No. :
<asp:TextBox ID="TextBox3" runat="server" Width="196px" ></asp:TextBox>
</p>
<p>
Contact Person Name :
<asp:TextBox ID="TextBox4" runat="server" Width="196px" ></asp:TextBox>
</p>
<p>
Total Amount Invoiced:
<asp:TextBox ID="TextBox5" runat="server" Width="193px" ></asp:TextBox>
</p>
<p>
Business partner Territory:
<asp:TextBox ID="TextBox6" runat="server" Width="174px" ></asp:TextBox>
</p>
<p>
Sales Employee:
<asp:TextBox ID="TextBox7" runat="server" Width="235px" ></asp:TextBox>
</p>
<p>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add"
Width="140px" />
<asp:Button ID="Button2" runat="server" Text="Cancel" Width="149px"
onclick="Button2_Click" />
</p>
</asp:Content>
Put your filtered customer into a DataTable(dt) and fill like this:
DropDownList2.DataTextField = "CustomerName";
DropDownList2.DataValueField = "CustomerID";
DropDownList2.DataSource = dt;
DropDownList2.DataBind();
The list2 will change its value once the list1 trigger the selectedindexchanged event.
protected void LoadOptions()
{
DataTable CardCode = new DataTable();
string id, name, newName, name2;
SqlConnection connection = new SqlConnection("Data Source=adfsadf;Initial Catalog=TestDatabse;Persist Security Info=True;User ID=asd;Password=asdf");
using (connection)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT T1.CardCode , T1.CardName, T2.OpprId,T1.CntctPrsn, T2.CprCode,T2.MaxSumLoc FROM OCRD T1 left join OOPR T2 on T1.CardCode=T2.CardCode" , connection);
adapter.Fill(CardCode);
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
id = CardCode.Rows[i]["CardCode"].ToString();
name = CardCode.Rows[i]["CardName"].ToString();
newName = id + " ---- " + name;
//name2 = id;
DropDownList1.Items.Add(new ListItem(newName, id));
//*******HERE*****//
DropDownList2.DataSource = CardCode;
DropDownList2.DataBind();
DropDownList2.DataValueField = "CardCode";
DropDownList2.DataTextField = "CntctPrsn";
//*******HERE*****//
}
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = DropDownList1.SelectedItem.Value;
SqlConnection connection = new SqlConnection("Data Source=mydtasrc;Initial Catalog=TestDatabs;Persist Security Info=True;User ID=asf;Password=asdfgh");
using (connection)
{
// SqlCommand theCommand = new SqlCommand("SELECT CardCode, CardName, OpprId, CprCode,MaxSumLoc FROM OOPR WHERE CardCode = #CardCode", connection);
SqlCommand theCommand = new SqlCommand("SELECT T1.CardCode , T1.CardName, T2.OpprId, T1.CntctPrsn,T2.CprCode FROM OCRD T1 left join OOPR T2 on T1.CardCode=T2.CardCode where T1.CardCode=#CardCode", connection);
connection.Open();
theCommand.Parameters.AddWithValue("#CardCode", selected);
theCommand.CommandType = CommandType.Text;
SqlDataReader theReader = theCommand.ExecuteReader();
if (theReader.Read())
{
this.TextBox1.Text = theReader["CardCode"].ToString();
this.TextBox2.Text = theReader["CardName"].ToString();
this.TextBox5.Text = theReader["CprCode"].ToString();
this.TextBox3.Text = theReader["OpprId"].ToString();
//*******AND HERE*****//
this.DropDownList2.SelectedValue = selected;
//*******AND HERE*****//
}
connection.Close();
}
}
On the left side, I have 3 labels that display the data according to the database. I want to whenever after I type in the data on the textbox and after clicking the submit button, the label will automatically refresh, and display the data. I do not want to click on the browser refresh button to refresh the labels. I only want to refresh the labels. Thanks
After clicking submit button(I do not want to refresh the page as if i refresh the page, the record created text will not be shown.)
After clicking refresh button.
error
MY SOURCE CODE
<table class="style1">
<tr>
<td class="style3">
<asp:Label ID="Label6" runat="server" Text="Event Announcement of the day"
ForeColor="Lime" style="text-decoration: underline" ></asp:Label>
<br />
<asp:Label ID="lblEvent1" runat="server" ForeColor="White"></asp:Label>
<br />
<asp:Label ID="lblEvent2" runat="server" ForeColor="White"></asp:Label>
<br />
<asp:Label ID="lblEvent3" runat="server" ForeColor="White"></asp:Label>
<br />
<br />
<br />
</td>
<td class="style2">
<asp:Label ID="lblEventType" runat="server" Text="Event Type" ForeColor="White"></asp:Label>
<asp:TextBox ID="txtEventType" runat="server"></asp:TextBox>
<br />
<asp:Label ID="lblEventName" runat="server" Text="Event Name" ForeColor="White"></asp:Label>
<asp:TextBox ID="txtEventName" runat="server"></asp:TextBox>
<br />
<asp:Label ID="lblStartDate" runat="server" Text="Start Date" ForeColor="White"></asp:Label>
: <asp:TextBox runat="server" id="txtStartDate" />
<br />
<asp:Label ID="lblEndDate" runat="server" Text="End Date" ForeColor="White"></asp:Label>
<asp:TextBox runat="server" id="txtEndDate" />
<br />
<br />
<br />
<asp:Button ID="txtSubmit" runat="server" onclick="txtSubmit_Click"
Text="Submit" />
</td>
</tr>
MY CODE BEHIND CODE
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string strConnString = ConfigurationManager.ConnectionStrings["ProjectConnectionString"].ConnectionString;
string str;
SqlCommand com;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
str = "select * from EVENT_ANNOUNCE where getdate() >= STARTDATE and cast(getdate() as Date) <= ENDDATE";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
var events = new List<string>();
if (reader.HasRows)
{
while (reader.Read())
events.Add(reader["EVENTNAME"].ToString());
}
if (events.Count >= 1)
lblEvent1.Text = events[0];
if (events.Count >= 2)
lblEvent2.Text = events[1];
if (events.Count >= 3)
lblEvent3.Text = events[2];
reader.Close();
con.Close();
}
}
private void insertEventRecord(string eventtype, string eventname, DateTime startdate, DateTime enddate)
{
try
{
string strConnectionString = ConfigurationManager.ConnectionStrings["ProjectConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "INSERT EVENT_ANNOUNCE(EVENTTYPE, EVENTNAME, STARTDATE, ENDDATE) Values(#EVENTTYPE, #EVENTNAME, #STARTDATE, #ENDDATE)";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValue("#EVENTTYPE", eventtype);
cmd.Parameters.AddWithValue("#EVENTNAME", eventname);
cmd.Parameters.AddWithValue("#STARTDATE", startdate);
cmd.Parameters.AddWithValue("#ENDDATE", enddate);
myConnect.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
lblSuccess.Visible = true;
lblSuccess.Text = "Record Created";
lblError.Visible = false;
bindEventGridView();
}
else
{
lblError.Visible = true;
lblError.Text = "Create Fail";
lblSuccess.Visible = false;
}
myConnect.Close();
}
catch (Exception)
{
lblError.Visible = true;
lblError.Text = "Please enter correct data";
lblSuccess.Visible = false;
}
}
protected void txtSubmit_Click(object sender, System.EventArgs e)
{
string eventtype = Convert.ToString(txtEventType.Text);
string eventname = Convert.ToString(txtEventName.Text);
string startdate = Convert.ToString(txtStartDate.Text);
string enddate = Convert.ToString(txtEndDate.Text);
DateTime datStartDate;
DateTime datEndDate;
if (DateTime.TryParseExact(startdate, new string[] { "dd/MM/yyyy" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out datStartDate)
&& (DateTime.TryParseExact(enddate, new string[] { "dd/MM/yyyy" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out datEndDate)))
{
insertEventRecord(eventtype, eventname, datStartDate, datEndDate);
System.Threading.Thread.Sleep(5000);
}
else
{
lblError.Visible = true;
lblError.Text = "Invalid Date";
lblSuccess.Visible = false;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
UpdateLabels();// code moved to a method
}
}
protected void txtSubmit_Click(object sender, System.EventArgs e)
{
// at the end of your code
txtEventType.Text = string.Empty;
txtEventName.Text = string.Empty;
// set all the text boxes empty like above
// update the label values
UpdateLabels();
}
public void UpdateLabels()
{
string strConnString = ConfigurationManager.ConnectionStrings["ProjectConnectionString"].ConnectionString;
string str;
SqlCommand com;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
str = "select * from EVENT_ANNOUNCE where getdate() >= STARTDATE and cast(getdate() as Date) <= ENDDATE";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
var events = new List<string>();
if (reader.HasRows)
{
while (reader.Read())
events.Add(reader["EVENTNAME"].ToString());
}
if (events.Count >= 1)
lblEvent1.Text = events[0];
if (events.Count >= 2)
lblEvent2.Text = events[1];
if (events.Count >= 3)
lblEvent3.Text = events[2];
reader.Close();
con.Close();
}
I am creating an application for a asp.net class that I am taking. One of the pages in the application needs to allow a user to search for a specific student via last name or user ID. When the student is found the page should display the students data and his/her class schedule.
I have gotten everything to work except for the class schedule. The approach I have taken (as we learned in class) was to get the query results via the SqlDataReader and bind it to a GridView. This is done in showStudentSchedule().
The query in this function returns the correct results when I test it against the DB I created, but the grid view displaying a students schedule doesn't show up on the page.
//StudentInformation.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="StudentInformation.aspx.cs" Inherits="StudentInformation" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<p>
<asp:Label ID="Label6" runat="server" Text="Search by Last Name: "></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:DropDownList ID="DropDownList1" runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True">
</asp:DropDownList>
</p>
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<asp:Label ID="Label2" runat="server"></asp:Label>
<br />
<asp:Label ID="Label3" runat="server"></asp:Label>
<br />
<asp:Label ID="Label4" runat="server"></asp:Label>
<br />
<asp:Label ID="Label5" runat="server"></asp:Label>
<asp:Panel ID="Panel1" runat="server">
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</asp:Panel>
</asp:Content>
//StudentInformation.aspx.cs
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 StudentInformation : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string userStr = TextBox1.Text;
int userInt;
bool isNum = int.TryParse(userStr, out userInt);
string sqlSelectFindUserByName;
if (isNum)
sqlSelectFindUserByName = string.Format("SELECT LastName FROM Personal_Info JOIN Students ON Personal_Info.ID = Students.Student_ID WHERE Personal_Info.ID = '{0}'", userInt);
else
sqlSelectFindUserByName = string.Format("SELECT LastName FROM Personal_Info JOIN Students ON Personal_Info.ID = Students.Student_ID WHERE Personal_Info.LastName LIKE '%{0}%'", userStr);
SqlConnection connection = new SqlConnection();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand commandFindUserByName = new SqlCommand(sqlSelectFindUserByName, connection);
connection.Open();
SqlDataReader readerFindUserByName = commandFindUserByName.ExecuteReader();
DropDownList1.Items.Clear();
DropDownList1.Items.Add("Please make a selection");
while (readerFindUserByName.Read())
DropDownList1.Items.Add(readerFindUserByName["LastName"].ToString());
if (DropDownList1.Items.Count == 2)
DropDownList1.SelectedIndex = 1;
DropDownList1_SelectedIndexChanged(null, null);
connection.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string nameLast = DropDownList1.SelectedItem.Value;
displayStudent(nameLast);
}
private void displayStudent(String nameLast)
{
clearStudentLabel();
int userInt;
bool isNum = int.TryParse(nameLast, out userInt);
SqlConnection connection = new SqlConnection();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string sqlSelectFindUserInfoByName;
sqlSelectFindUserInfoByName = string.Format("SELECT ID, FirstName, LastName, City, Phone FROM Personal_Info WHERE LastName LIKE '%{0}%'", nameLast);
SqlCommand commandFindUserInfo = new SqlCommand(sqlSelectFindUserInfoByName, connection);
connection.Open();
SqlDataReader readerFindUserInfo = commandFindUserInfo.ExecuteReader();
int i = 0;
while (readerFindUserInfo.Read())
{
Label1.Text = "Student ID: " + readerFindUserInfo["ID"].ToString();
Label2.Text = "First name: " + readerFindUserInfo["FirstName"].ToString();
Label3.Text = "Last name: " + readerFindUserInfo["LastName"].ToString();
Label4.Text = "City: " + readerFindUserInfo["City"].ToString();
Label5.Text = "Phone: " + readerFindUserInfo["Phone"].ToString();
}
connection.Close();
showStudentSchedule(userInt);
}
private void showStudentSchedule(int id)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string sqlSelectFindUserInfoByName = string.Format("SELECT Class_Schedule.Section_ID, Class_Schedule.Course_ID, Class_Schedule.Days, Class_Schedule.Time, CASE WHEN Personal_Info.FirstName IS NULL THEN 'Staff' ELSE (Personal_Info.LastName + Personal_Info.FirstName) END AS Name FROM Class_Schedule JOIN Student_Enrollment ON Class_Schedule.Section_ID = Student_Enrollment.Section_ID JOIN Personal_Info ON Class_Schedule.Instructor_ID = Personal_Info.ID WHERE Student_Enrollment.Student_ID = {0}", id);
SqlCommand commandFindUserInfo = new SqlCommand(sqlSelectFindUserInfoByName, connection);
connection.Open();
SqlDataReader readerFindUserInfo = commandFindUserInfo.ExecuteReader();
GridView1.DataSource = readerFindUserInfo;
GridView1.DataBind();
/*
string connectionString = "Data Source=LocalHost;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=sa_0001";
string commandString = "Select * from Customers";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(commandString);
conn.Open();
command.Connection = conn;
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
GridView1.DataSource = reader;
GridView1.DataBind();
*/
}
private void clearStudentLabel()
{
Label1.Text = "";
Label2.Text = "";
Label3.Text = "";
Label4.Text = "";
Label5.Text = "";
}
}
Try this out:
SqlConnection connection = new SqlConnection();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand command = new SqlCommand(sqlSelectFindUserByName);
connection.Open();
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
GridView1.DataSource = reader;
GridView1.DataBind();