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();
}
Related
I am using 4 radiobuttons as options to a question. The question and the radiobuttons are refreshed after button click. The checked radiobutton text is compared with the answer and if it matches, a counter is increased. I have found that when I check a radiobutton first time the corresponding radiobutton on the next question will be checked already and if it is the answer it will increase the counter and if i change it to check another radiobutton which is the actual answer the counter is not increased. Do I have to specify any property for the updatepanel that i am using to refresh the question. Thnk you for time to read this long one.
This is my aspx code
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<style>
.con{
width:70%;
margin:auto;
}
.testres{
display:none;
}
.btnHome{
display:none;
color:rgb(0,159,37);
text-decoration:none;
background:none;
border:1px solid grey;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div class="con">
<div class="subject-name">
<asp:Label runat="server" Text="Subject : " /><asp:Label ID="lblSubjectName" runat="server" Text="" />
</div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="question-options">
<fieldset>
<legend><asp:Label ID="lblQ" runat="server" Text="Q.No. "/><asp:Label ID="lblQuesNo" runat="server" Text="" /></legend>
<asp:Panel ID="question" runat="server">
<asp:Label ID="lblQues" runat="server" Text="" />
<ul style="list-style-type:none">
<li><asp:RadioButton ID="RadioButton1" runat="server" AutoPostBack="false" GroupName="answer" Text="" /></li>
<li><asp:RadioButton ID="RadioButton2" runat="server" AutoPostBack="false" GroupName="answer" Text="" /></li>
<li><asp:RadioButton ID="RadioButton3" runat="server" AutoPostBack="false" GroupName="answer" Text="" /></li>
<li><asp:RadioButton ID="RadioButton4" runat="server" AutoPostBack="false" GroupName="answer" Text="" /></li>
</ul>
</asp:Panel>
<asp:Panel ID="Panel1" CssClass="testres" runat="server">
<asp:Label ID="Label1" runat="server" Text="Correct Answers : "></asp:Label>
<asp:Label ID="Label2" runat="server" Text=""></asp:Label>
</asp:Panel>
<asp:Button ID="btnNext" runat="server" Text="Next" OnClick="btnNext_Click"/>
<asp:Button ID="btnHome" runat="server" Text="Home" CssClass="btnHome" OnClick="btnHome_Click"/>
</fieldset>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Content>
This is code behind
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class OnlineTest_Question : System.Web.UI.MasterPage
{
SqlConnection con = new SqlConnection("Password=password#123;Persist Security Info=True;User ID=sa;Initial Catalog=MyDatabasae;Data Source=.");
SqlCommand cmd=new SqlCommand();
SqlDataReader rdr;
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
DataTable dt3 = new DataTable();
static int rowcount=0;
static int totalrowcount;
string id = "";
string subname = "";
string correctans = "";
int i = 1;
static int correctcount = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
cmd.CommandText = "select subject from subjectstb where subid='" + Request.QueryString["sid"] + "'";
cmd.Connection = con;
con.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
subname = rdr["subject"].ToString();
}
rdr.Close();
con.Close();
lblSubjectName.Text = subname;
try
{
cmd.CommandText = "select * from questionstb where subject='" + Request.QueryString["sid"] + "'";
con.Open();
cmd.Connection = con;
rdr = cmd.ExecuteReader();
dt.Load(rdr);
rdr.Close();
totalrowcount = dt.Rows.Count;
lblQues.Text = dt.Rows[0]["question"].ToString();
id = dt.Rows[0]["qid"].ToString();
cmd.CommandText = "select * from optionstb where qid='" + id + "'";
rdr = cmd.ExecuteReader();
dt1.Load(rdr);
RadioButton1.Text = dt1.Rows[0]["choice"].ToString();
RadioButton2.Text = dt1.Rows[1]["choice"].ToString();
RadioButton3.Text = dt1.Rows[2]["choice"].ToString();
RadioButton4.Text = dt1.Rows[3]["choice"].ToString();
lblQuesNo.Text = (rowcount + 1).ToString();
correctans = dt1.Rows[0]["correct"].ToString();
if (RadioButton1.Checked == true && RadioButton1.Text == correctans)
{
correctcount = correctcount + 1;
}
else if (RadioButton2.Checked == true && RadioButton2.Text == correctans)
{
correctcount = correctcount + 1;
}
else if (RadioButton3.Checked == true && RadioButton3.Text == correctans)
{
correctcount = correctcount + 1;
}
else if (RadioButton4.Checked == true && RadioButton4.Text == correctans)
{
correctcount = correctcount + 1;
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
if(rowcount<5)
{
if(rowcount>=totalrowcount)
{
lblQuesNo.Text = "Not Available";
lblQues.Text = "No more questions available.";
}
else
{
cmd.CommandText = "select * from questionstb where subject='" + Request.QueryString["sid"] + "'";
con.Open();
cmd.Connection = con;
rdr = cmd.ExecuteReader();
dt3.Load(rdr);
rdr.Close();
totalrowcount = dt3.Rows.Count;
lblQuesNo.Text = (rowcount+1).ToString();
lblQues.Text = dt3.Rows[rowcount]["question"].ToString();
dt1.Load(rdr);
id = dt3.Rows[rowcount]["qid"].ToString();
cmd.CommandText = "select * from optionstb where qid='" + id + "'";
rdr = cmd.ExecuteReader();
DataTable dt2 = new DataTable();
dt2.Load(rdr);
rdr.Close();
RadioButton1.Text = dt2.Rows[0]["choice"].ToString();
RadioButton2.Text = dt2.Rows[1]["choice"].ToString();
RadioButton3.Text = dt2.Rows[2]["choice"].ToString();
RadioButton4.Text = dt2.Rows[3]["choice"].ToString();
cmd.CommandText = "select * from optionstb where qid='"+id+"'";
rdr = cmd.ExecuteReader();
DataTable d=new DataTable();
d.Load(rdr);
correctans = d.Rows[0]["correct"].ToString();
if (RadioButton1.Checked == true && RadioButton1.Text == correctans)
{
correctcount = correctcount + 1;
}
else if (RadioButton2.Checked == true && RadioButton2.Text == correctans)
{
correctcount = correctcount + 1;
}
else if (RadioButton3.Checked == true && RadioButton3.Text == correctans)
{
correctcount = correctcount + 1;
}
else if (RadioButton4.Checked == true && RadioButton4.Text == correctans)
{
correctcount = correctcount + 1;
}
rowcount = rowcount + 1;
}
}
else
{
con.Close();
Label2.Text = correctcount.ToString();
question.Style.Add("display","none");
Panel1.Style.Add("display", "block");
btnNext.Text = "";
lblQ.Text = "Result";
btnHome.Style.Add("display", "block");
lblQuesNo.Text = "";
btnNext.Style.Add("background", "none");
btnNext.Style.Add("border", "none");
}
}
protected void btnHome_Click(object sender, EventArgs e)
{
rowcount = 0;
correctcount = 0;
Response.Redirect("testselect.aspx");
}
}
You should put the code chunk that controls this process. Otherwise we can not help you.
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?
Below is my ASP.net code with my Listview Control with a checkbox absentCheckBox
<asp:ListView ID="student_list" runat="server" DataSourceID="view_students">
<ItemTemplate>
<tr style="">
<td>
<asp:Label Text='<%# Eval("assignment_id") %>' runat="server" ID="assignment_idLabel" />
</td>
<td>
<asp:Label Text='<%# Eval("user_id") %>' runat="server" ID="user_idLabel" />
</td>
<td>
<asp:TextBox Text='<%# Eval("result_percentage") %>' runat="server" ID="result_percentageTextBox" />
</td>
<td>
<asp:CheckBox Checked='<%# Eval("absent") %>' runat="server" ID="absentCheckBox" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:Button ID="add_results" runat="server" Text="Update Results" OnClick="add_results_Click" CssClass="blue" />
Below is my C# code behind where I am trying to loop through the checkboxes in
protected void add_results_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in student_list.Items)
{
int student_id = 0;
Label student_id_lbl = (Label)item.FindControl("user_idLabel");
student_id = Convert.ToInt32(student_id_lbl.Text);
int assignment_id = 0;
Label assignment_id_lbl = (Label)item.FindControl("assignment_idLabel");
assignment_id = Convert.ToInt32(assignment_id_lbl.Text);
int result = 0;
TextBox result_total_ddl = item.FindControl("result_percentageTextBox") as TextBox;
if (result_total_ddl != null)
{
if (Int32.TryParse(result_total_ddl.Text, out result))
{
}
else
{
}
}
bool absent = false;
CheckBox absent_chk = item.FindControl("absentCheckBox") as CheckBox;
absent = Convert.ToBoolean(absent_chk.Text);
if (result < 0 || result > 100)
{
feedback.Text = "Please enter an assignment total in between 0 - 100 you have entered : <b>" + result + "</b>.";
}
else
{
String connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
String query = "UPDATE assignments_vs_users SET result_percentage = #result_percentage, absent = #absent WHERE assignment_id = #assignment_id AND user_id = #student_id; ";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("#result_percentage", result);
myCommand.Parameters.AddWithValue("#assignment_id", assignment_id);
myCommand.Parameters.AddWithValue("#student_id", student_id);
myCommand.Parameters.AddWithValue("#absent", absent);
myCommand.ExecuteNonQuery();
myConnection.Close();
}
}
}
How can I use absent within myCommand.Parameters.AddWithValue("#absent", absent); so it updates the database column for absent if the checkbox is ticked to true
i have the code below.when i add a data in particular day cell.the data inserts in another daycell.please help.what is the problem in my code.why sometimes the data is inserted properly nad sometimes it is inserted in some other day cell
eg:
if i insert date in 23/2
the data inserted in
19/3
private DataSet GetData()
{
string strcon = ConfigurationManager.ConnectionStrings["ConnectionCommon"].ConnectionString;
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlDataAdapter ad = new SqlDataAdapter("PrcScheduler", con);
DataSet ds = new DataSet();
ad.Fill(ds);
con.Close();
return ds;
}
//code to insert the data in table
protected void Btn_AddTask_Click(object sender, EventArgs e)
{
string strcon = ConfigurationManager.ConnectionStrings["ConnectionCommon"].ConnectionString;
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlCommand cmd = new SqlCommand("prcinsertscheduler", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Schedule_title", txtTitle.Text.ToString());
cmd.Parameters.AddWithValue("#Schedule_Date", hdnSelectedDate.Value);
cmd.ExecuteNonQuery();
con.Close();
txtTitle.Text = "";
}
//dayrender event
protected void calendar12_DayRender(object sender, DayRenderEventArgs e)
{
DataSet ds = GetData();
string link = "<a href=' Calendar.aspx?Schedule_ID=";
string s = e.Day.Date.ToShortDateString();
e.Cell.Text = e.Day.Date.Day.ToString() + "<BR>";
LiteralControl l = new LiteralControl();
l.Text = e.Day.Date.Day.ToString() + "<BR>";
e.Cell.Controls.Add(l);
//retriving the data in calenar cel
foreach (DataRow row in ds.Tables[0].Rows)
{
string scheduledDate = Convert.ToDateTime(row["Schedule_Date"]).ToShortDateString();
if (scheduledDate.Equals(s))
{
LinkButton lb = new LinkButton();
lb.Text = link + (int)row["Schedule_ID"] + "'>" + row["Schedule_title"] as String + "</a>" + "<BR>";
e.Cell.Controls.Add(lb);
}
}
HtmlAnchor anchor = new HtmlAnchor();
anchor.InnerHtml = "Add";
string method = "ShowAddTaskPane(event,'" + e.Day.Date.ToShortDateString() + "')";
anchor.HRef = "#";
anchor.Attributes.Add("onclick", method);
//To add the htmlanchor in the panel and show that on mouseover
Panel p1 = new Panel();
p1.ID = "p" + e.Day.DayNumberText + e.Day.Date.Month.ToString(); ;
p1.Attributes.Add("style", "display:none;");
p1.Controls.Add(anchor); ;
e.Cell.Controls.Add(p1);
e.Cell.Attributes.Add("onmouseover", "ShowInfo('" + p1.ClientID + "')");
e.Cell.Attributes.Add("onmouseout", "HideInfo('" + p1.ClientID + "')");
}
protected void btncancel_Click(object sender, EventArgs e)
{
calendar12.Visible = true;
}
}
}
.aspx
<title></title>
<script type="text/javascript">
function ShowAddTaskPane(e, selectedDate) {
debugger;
var ev = e || window.event;
document.getElementById("AddTaskPane").style.visibility = 'visible';
document.getElementById("AddTaskPane").style.top = ev.clientY;
document.getElementById("AddTaskPane").style.left = ev.clientX;
}
// function trimByWord(sentence) {
// var result = sentence;
// var resultArray = result.split(” “);
// if(resultArray.length > 10){
// resultArray = resultArray.slice(0, 10);
// result = resultArray.join(” “) + “…”;
// }
//return result;
//}
function ShowInfo(id) {
var div = document.getElementById(id);
document.getElementById("hdnSelectedDate").value = div.innerHTML.match(/'([^']+)'/)[1];
div.style.display = "block";
}
function HideInfo(id) {
var div = document.getElementById(id);
div.style.display = "none";
}
</script>
<table>
<tr>
<td>
<asp:TextBox ID="txtTitle" runat="server" TextMode="MultiLine" Rows="5" />
</td>
</tr>
<tr>
<td>
<asp:Button ID="Btn_AddTask" runat="server" Text="Save" Width="44px" OnClick="Btn_AddTask_Click" />
<asp:Button ID="btncancel" runat="server" Text="Cancel"
onclick="btncancel_Click" />
<asp:Button ID="btnoption" runat="server" Text="Option" />
</td>
</tr>
</table>
</div>
<div>
<table>
<tr>
<td>
<asp:Calendar ID="calendar12" runat="server" ondayrender="calendar12_DayRender"
BackColor="White" BorderColor="Black" BorderStyle="Solid" CellSpacing="1"
Font-Names="Verdana" Font-Size="9pt" ForeColor="Black" Height="291px"
NextPrevFormat="ShortMonth" Width="416px">
<DayHeaderStyle Font-Bold="True" Font-Size="8pt" ForeColor="#333333"
Height="8pt" />
<DayStyle BackColor="#CCCCCC" />
<NextPrevStyle Font-Bold="True" Font-Size="8pt" ForeColor="White" />
<OtherMonthDayStyle ForeColor="#999999" />
<SelectedDayStyle BackColor="#333399" ForeColor="White" />
<TitleStyle BackColor="#333399" BorderStyle="Solid" Font-Bold="True"
Font-Size="12pt" ForeColor="White" Height="12pt" />
<TodayDayStyle BackColor="#999999" ForeColor="White" />
</asp:Calendar>
<asp:HiddenField ID="hdnSelectedDate" runat="server" />
</td>
</tr>
</table>
</div>
</form>
</body>
</ht
It might be an issue with date formatting. Your hdnSelectedDate.Value is a text and needs to be in proper format. Its input is generated by ShowInfo and you need to make sure that both the input is correct and the Value is converted to a valid date representation.
I am making an application about article publication. I have 2 tables
"artikulli"
id int Unchecked
tema varchar(250) Checked
abstrakti text
data_publikimit date
path varchar(350)
keywords varchar(350)
kategoria_id int
departamenti_id int
"kategorite"
id int Unchecked
emertimi varchar(350)
I want to display in a dropdown list all values of field "emertimi" and when the user selects one value to save id of that value in table "artikulli".
I have done the following, but I have the problem with syntax because I am using DATALIST.
public partial class AddArticle : System.Web.UI.Page
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Attributes.Add("enctype", "multipart/form-data");
try
{
if (!IsPostBack)
{
Bind();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
public void Bind()
{
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
protected void datalist2_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
TextBox txtTema = e.Item.FindControl("txtTema") as TextBox;
TextBox txtAbstrakti = e.Item.FindControl("txtAbstrakti") as TextBox;
TextBox txtData = e.Item.FindControl("txtData") as TextBox;
TextBox txtKeywords = e.Item.FindControl("txtKeywords") as TextBox;
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection conn = new SqlConnection(connection);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "Insert into artikulli(tema,abstrakti,data_publikimit,path,keywords,kategoria_id) values (#tema,#abstrakti,#data,#filename,#keywords,#kategoria)";
command.Parameters.Add(new SqlParameter("#tema", txtTema.Text));
command.Parameters.Add(new SqlParameter("#abstrakti", txtAbstrakti.Text));
command.Parameters.Add(new SqlParameter("#data", txtData.Text));
command.Parameters.Add(new SqlParameter("#keywords", txtKeywords.Text));
command.Parameters.Add(new SqlParameter("#kategoria", drpdKategoria.SelectedValue));
FileUpload FileUploadArtikull = (FileUpload)e.Item.FindControl("FileUploadArtikull");
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximumi i madhesise se file qe lejohet eshte 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
//add parameters
command.Parameters.AddWithValue("#filename", filename);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
Bind();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Ju nuk keni ngarkuar asnje artikull');", true);
}
}
}
AddArtikull.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="AddArtikull.aspx.cs" Inherits="AddArticle" MasterPageFile="~/MasterPage2.master" %>
<asp:Content ID="content2" ContentPlaceholderID=ContentPlaceHolder2 runat="server">
<asp:DataList ID="datalist2" runat="server"
onitemcommand="datalist2_ItemCommand" >
<FooterTemplate>
<section id="main" class="column" runat="server" style="width:900px;">
<article class="module width_full" style="width:900px;">
<header><h3 style="text-align: center">Shto Artikull </h3></header>
<div id="Div1" class="module_content" runat="server">
<asp:Label ID="Label1" runat="server" style="font-weight: 700">Tema</asp:Label>
<fieldset>
<asp:TextBox ID="txtTema" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorTema" runat="server"
ControlToValidate="txtTema" Display="Dynamic"
ErrorMessage="Kjo fushe eshte e nevojshme" style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset><br />
<asp:Label ID="Label6" runat="server" style="font-weight: 700">Abstrakti</asp:Label>
<fieldset>
<asp:TextBox ID="txtAbstrakti" style="height:250px;" Textmode="Multiline" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorAbstrakti" runat="server"
ControlToValidate="txtAbstrakti" ErrorMessage="Kjo fushe eshte e nevojshme"
style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset>
<asp:Label ID="lblData" runat="server" style="font-weight: 700">Data e Publikimit</asp:Label>
<fieldset>
<asp:TextBox ID="txtData" runat="server"></asp:TextBox>
</fieldset>
<asp:Label ID="lblKeywords" runat="server" style="font-weight: 700">Keywords</asp:Label>
<fieldset>
<asp:TextBox ID="txtKeywords" runat="server"></asp:TextBox>
</fieldset>
<br />
<asp:Label ID="Label5" runat="server" style="font-weight: 700">Kategoria</asp:Label>
<div>
<asp:DropDownList ID="drpdKategoria" runat="server" AutoPostBack="false"></asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Insert"
/>
</div><br />
<strong>Ngarko Artikull</strong><br />
<asp:FileUpload ID="FileUploadArtikull" runat="server" /><br />
<br />
<asp:Button ID="btnInsert" runat="server" CommandName="Insert" Text="Shto" />
</div>
</article>
</section>
</FooterTemplate>
</asp:DataList>
</asp:Content>
It shows this error:
Compiler Error Message: CS0103: The name 'e' does not exist in the
current context
In this line:
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
In your bind method you are calling an object e that doesn't exist. If the dropdownlist isn't inside a bound element, you can just reference the front code directly, e.g.
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
without finding the control as long as it is runat="server"
UPDATE
Okay, so you need to add an OnItemCreated event in your datalist
OnItemCreated="datalist2_OnItemCreated"
Then in that method you need this
protected void datalist2_OnItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id";
drpdKategoria.DataTextField = "emertimi";
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
}
That will work for if you only have the footer, if you add an itemtemplate then you just need to get rid of the check for the footer and on each item creation grab that dropdownlist for that item