Avoiding PostBack in asp - asp.net

I want to avoid postback when my button event fired. Due to postback my List gets empty again. Kindly Help me out with this. What should i do to avoid postback. I am using ASP button.
Here is my button method
id = Convert.ToInt32(Request.QueryString["id"].ToString());
venues.Add(id);
foreach (int item1 in venues)
{
if (!hashset.Add(item1))
{
Response.Write("<script>alert('Duplicate Items');</script>");
break;
}
else
{
foreach (var items in venues)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Venues where VenueID = '" + items + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter ds = new SqlDataAdapter(cmd);
ds.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
Name = dr["Name"].ToString();
Address = dr["Address"].ToString();
Picture = dr["Picture"].ToString();
Price = dr["Price"].ToString();
}
con.Close();
if (Request.Cookies["aa"] == null)
{
Response.Cookies["aa"].Value = Name.ToString() + "," + Address.ToString() + "," + Picture.ToString() + "," + Price.ToString();
Response.Cookies["aa"].Expires = DateTime.Now.AddDays(1);
}
else
{
Response.Cookies["aa"].Value = Request.Cookies["aa"].Value + "|" + Name.ToString() + "," + Address.ToString() + "," + Picture.ToString() + "," + Price.ToString();
Response.Cookies["aa"].Expires = DateTime.Now.AddDays(1);
}
}
}
}
}

Related

Nested foreach() messing up

Good Day, guys.
I'm currentl making a full page overlay for navigation and I've been trying to figure out this problem for the past 2 days regarding my nested foreach() loops.
I have these pages which may be linked with posts. and here is what I'm trying to achieve:
Home Page
Technologies Page
Post 1/ Post 2/ Post3
Contact Us Page
About Us Page
But what I'm getting is:
Home Page
Technologies Page
Post 1/ Post 2/ Post3
Contact Us Page
Post 1/ Post 2/ Post3
About Us Page
Post 1/ Post 2/ Post3
Here are my code:
public DataTable GetMain()
{
string sql = "SELECT Id,Title,Slug from Pages";
SqlCommand SQLComm = new SqlCommand(sql, con);
SqlDataAdapter SQLAd = new SqlDataAdapter(SQLComm);
DataTable dt = new DataTable();
SQLAd.Fill(dt);
return dt;
}
private void GetAll()
{
DataTable dt = new DataTable();
HyperLink newhyperlink = new HyperLink();
Label newlabel = new Label();
foreach (DataRow row in GetMain().Rows)
{
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = #"<li class""dropdown"" data-toggle=""collapse""";
newlabel = new Label();
newhyperlink.ID = "Main";
MainMenu.Controls.Add(newhyperlink);
newhyperlink.Text = row["Title"].ToString();
newhyperlink.NavigateUrl = row["Slug"].ToString();
newhyperlink = new HyperLink();
html.Append("></li>");
html.Append("<ul class=\"list-group\">");
var sql2 = "SELECT po.Id as PostId, po.Slug as PostSlug, po.Title as PostTitle, pa.Slug as PageSlug, pa.Id as PageId FROM Posts po " +
"LEFT JOIN PagesPostsMap m ON po.Id = m.PostId " +
"LEFT JOIN Pages pa ON m.PageId = pa.Id " +
"WHERE pa.Id = "+row["Id"] + "";
SqlDataAdapter SQLAd = new SqlDataAdapter(sql2, con);
SQLAd.Fill(dt2);
foreach (DataRow row2 in dt2.Rows)
{
object value = row2["PostId"];
if (value != DBNull.Value)
{
if (row["Id"] != row2["PageId"])
{
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = #"<li class""dropdown-menu""";
newlabel = new Label();
newhyperlink.ID = "Sub" + i.ToString();
MainMenu.Controls.Add(newhyperlink);
newhyperlink.Text = row2["PostTitle"].ToString();
newhyperlink.NavigateUrl = row2["PageSlug"].ToString() + "/" + row2["PostSlug"].ToString();
newhyperlink = new HyperLink();
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = "</li>";
newlabel = new Label();
}
}
}
}
}
I'm sorry if the the classes and stuff are not adding up. I'm still trying to figure out how css and JS works.
And thank for helping me.
Your code is actually just doing what you tell it to do. For every row in your GetMain, you order everything in your dt2 (datatable2). If you want what you try to achive, you have to set a condition and put your second foreach into that condition.
if(tech parts row)
{
"your second foreach"
}
If I missunderstand anything, feel free to add more info
public DataTable GetMain()
{
string sql = "SELECT Id,Title,Slug from Pages";
SqlCommand SQLComm = new SqlCommand(sql, con);
SqlDataAdapter SQLAd = new SqlDataAdapter(SQLComm);
DataTable dt = new DataTable();
SQLAd.Fill(dt);
return dt;
}
private void GetAll()
{
DataTable dt = new DataTable();
HyperLink newhyperlink = new HyperLink();
Label newlabel = new Label();
foreach (DataRow row in GetMain().Rows)
{
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = #"<li class""dropdown"" data-toggle=""collapse""";
newlabel = new Label();
newhyperlink.ID = "Main";
MainMenu.Controls.Add(newhyperlink);
newhyperlink.Text = row["Title"].ToString();
newhyperlink.NavigateUrl = row["Slug"].ToString();
newhyperlink = new HyperLink();
html.Append("></li>");
html.Append("<ul class=\"list-group\">");
var sql2 = "SELECT po.Id as PostId, po.Slug as PostSlug, po.Title as PostTitle, pa.Slug as PageSlug, pa.Id as PageId FROM Posts po " +
"JOIN PagesPostsMap m ON po.Id = m.PostId " +
"JOIN Pages pa ON m.PageId = pa.Id " +
"WHERE pa.Id = "+row["Id"] + "";
SqlDataAdapter SQLAd = new SqlDataAdapter(sql2, con);
SQLAd.Fill(dt2);
foreach (DataRow row2 in dt2.Rows)
{
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = #"<li class""dropdown-menu""";
newlabel = new Label();
newhyperlink.ID = "Sub" + i.ToString();
MainMenu.Controls.Add(newhyperlink);
newhyperlink.Text = row2["PostTitle"].ToString();
newhyperlink.NavigateUrl = row2["PageSlug"].ToString() + "/" + row2["PostSlug"].ToString();
newhyperlink = new HyperLink();
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = "</li>";
newlabel = new Label();
}
}
}

Label does not show up in asp.net

I have a label in asp.net page and change its text in certain situations. Here is the code:
<asp:Label ID="errorMessage" runat="server" Text="Label" Visible="False"></asp:Label>
errorMessage.Text = MyGlobals.student.registerCourse(c, ref addList, course).ToString();
errorMessage.ForeColor = System.Drawing.Color.Red;
errorMessage.Visible = true;
When i debugged, i saw that MyGlobals.student.registerCourse(c, ref addList, course).ToString() method returns my error message well. Then i set the label visible, but when page loads i cannot see the label. Also, while debugging i saw that "textsetbyaddparsedsubobject" property of the label is false. Can that be the problem? Why is not the label being showed in my page? Can anyone help?
Thanks.
Edit: Here is the full code:
protected void bSubmitChanges_Click1(object sender, EventArgs e)
{
Userfunctions function = new Userfunctions();
List<string> dropList = new List<string>();
List<string> addList = new List<string>();
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
SqlCommand cmd;
con.Open();
string ID = MyGlobals.currentID;
try
{
for (int i = 1; i <= 6; i++)
{
string course;
if ((course = boxCRN(i)) != "")
{
cmd = new SqlCommand("select count (*) from CourseTable where CRN=#course", con);
cmd.Parameters.AddWithValue("#course", course);
int result = Convert.ToInt32(cmd.ExecuteScalar());
if (result > 0)
{
cmd = new SqlCommand("select * from CourseTable where CRN=#course", con);
cmd.Parameters.AddWithValue("#course", course);
cmd.ExecuteScalar();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
string query = "SELECT * FROM CourseTable WHERE CourseCode='" + dr["CourseCode"] + "' AND CourseNumber='" + dr["CourseNumber"] + "' AND Term='" + dr["Term"] + "'";
cmd = new SqlCommand(query, con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0];
cmd = new SqlCommand("select * from PrereqTable where CourseCode='" + dr["CourseCode"] + "' AND CourseNumber='" + dr["CourseNumber"] + "' AND Term='" + dr["Term"] + "'", con);
da2 = new SqlDataAdapter(cmd);
dt2 = new DataTable();
da2.Fill(dt2);
List<string> pre = new List<string>();
foreach (DataRow dr5 in dt2.Rows)
{
pre.Add(Convert.ToString(dr5["pCourseCode"]) + Convert.ToString(dr5["pCourseNumber"]));
}
Course c = new Course(dr2["InstructorID"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
c.addPrereq(pre);
string message = MyGlobals.student.registerCourse(c, ref addList, course).ToString();
errorMessage.Text = message;
errorMessage.ForeColor = System.Drawing.Color.Red;
errorMessage.Visible = true;
Label1.Visible = true;
Label1.Text = "asdasdasd";
}
}
}
}
}
catch (Exception) { }
for (int i = 0; i < showCourses.Rows.Count; i++)
{
string a = ((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue;
if (((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue == "1")
{
string courseCode = showCourses.Rows[i].Cells[1].Text, courseNumber = showCourses.Rows[i].Cells[2].Text;
SqlCommand com = new SqlCommand("select * from CourseTable where CourseCode=#courseCode and CourseNumber=#courseNumber", con);
com.Parameters.AddWithValue("courseCode", courseCode);
com.Parameters.AddWithValue("courseNumber", courseNumber);
try
{
SqlDataAdapter da2 = new SqlDataAdapter(com);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0];
Course c = new Course(dr2["InstructorID"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
Register reg = new Register(c, MyGlobals.student);
MyGlobals.student.dropCourse(reg);
dropList.Add(showCourses.Rows[i].Cells[1].Text + showCourses.Rows[i].Cells[2].Text);
}
catch (Exception) { }
}
}
foreach (string course in dropList)
{
for (int i = 0; i < MyGlobals.student.getRegistered().Count; i++ )
{
if (MyGlobals.student.getRegistered()[i].getCourse().getCode().ToString() + MyGlobals.student.getRegistered()[i].getCourse().getNumber().ToString() == course)
MyGlobals.student.dropCourse(MyGlobals.student.getRegistered()[i]);
}
cmd = new SqlCommand("delete from RegisterTable where StudentID='" + MyGlobals.currentID + "' and CourseCode='" + course.Substring(0, course.Length - 3) + "' and CourseNumber='" + course.Substring(course.Length - 3, 3) + "'", con);
cmd.ExecuteNonQuery();
}
try
{
foreach (string courses in addList)
{
string courseCode = "";
string courseNumber = "";
string term = MyGlobals.currentTerm + " " + MyGlobals.currentYear;
string q = ("select CourseCode from CourseTable where CRN=#courses");
string grade = "";
SqlCommand command = new SqlCommand(q, con);
command.Parameters.AddWithValue("#courses", courses);
courseCode = Convert.ToString(command.ExecuteScalar());
q = ("select CourseNumber from CourseTable where CRN=#courses");
command = new SqlCommand(q, con);
command.Parameters.AddWithValue("#courses", courses);
courseNumber = Convert.ToString(command.ExecuteScalar());
cmd = new SqlCommand("insert into RegisterTable (CourseCode,CourseNumber,Term,StudentID,Grade) values(#courseCode,#courseNumber,#term, #ID,'U')", con);
cmd.Parameters.AddWithValue("#courseCode", courseCode);
cmd.Parameters.AddWithValue("#courseNumber", courseNumber);
cmd.Parameters.AddWithValue("#term", term);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#grade", grade);
cmd.ExecuteNonQuery();
}
}
catch (Exception) { }
con.Close();
Response.Redirect("AddDropClasses.aspx");
}
}
And the registerCourse function:
public string registerCourse(Course course, ref List <string> addList, string crn) {
bool registered = true;
string message ="";
foreach (string s in course.getTime())
{
Userfunctions f = new Userfunctions();
foreach (Register r in this.register) {
if (r.getCourse().getTerm() == MyGlobals.currentTerm.ToString() + " " + MyGlobals.currentYear.ToString() && !f.TimeCheck(s, r.getCourse().getTime()))
{
registered = false;
message = "Time conflict";
}
}
}
if (registered) {
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string id = MyGlobals.currentID;
SqlCommand cmd = new SqlCommand("SELECT count (*) from RegisterTable where CourseCode ='" + course.getCode() +"' and CourseNumber='" + course.getNumber() + "' and Term='" + course.getTerm()+"'" , con);
cmd.Parameters.AddWithValue("#id", id);
int active = Convert.ToInt32(cmd.ExecuteScalar());
if (active >= Convert.ToInt32(course.getCapacity())){
registered = false;
message = "Not enough capacity";
}
if (registered) {
foreach (string s in course.getPrerequisites()) {
if (!hasPassedCourse(s)) {
registered = false;
message = "Prerequisite error";
}
}
}
}
if (registered)
{
Register reg = new Register(course, MyGlobals.student);
MyGlobals.student.addToSchedule(reg);
addList.Add(crn);
}
return message;
}
Remove below line
Response.Redirect("AddDropClasses.aspx");
it will load your page again as new page
When you have Visible="false" set on the control then the control properties may not been instatiated fully.
I would try hiding the control using, errorMessage.Visible=false in the code-behind in your Page_Load instead.

There is no row at position 0 error at asp.net

I was writing a web based program and this is my authentication page. It was working fine but suddenly it started to give that error.
Here is my code:
else if (LoginAs.SelectedValue == "Student")
{
string tableName = "StudentTable";
String name = "", surname = "", email = "";
string query = "Select level from " + tableName + " where ID='" + idBox.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
string level = Convert.ToString(cmd.ExecuteScalar());
CreateUser(con, tableName, ref name, ref surname, ref email);
query = "Select program from " + tableName + " where ID='" + idBox.Text + "'";
cmd = new SqlCommand(query, con);
string program = Convert.ToString(cmd.ExecuteScalar());
MyGlobals.student = new Student(Convert.ToInt32(idBox.Text), "Active", email, name, surname, password, level, program);
MyGlobals.currentID = idBox.Text;
query = "Select * from RegisterTable where StudentID='" + idBox.Text + "'";
cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
query = "SELECT * FROM CourseTable WHERE CourseCode='" + dr["CourseCode"] + "' AND CourseNumber='" + dr["CourseNumber"] + "' AND Term='" + dr["Term"] + "'";
cmd = new SqlCommand(query, con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0]; //ERROR COMES AT HERE
Course course = new Course(dr2["InstructorName"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
Register reg = new Register(course, MyGlobals.student);
MyGlobals.student.addToSchedule(reg);
}
int num = (int)Application["OnlineUsers"];
Response.Redirect("Student.aspx");
}
Can anyone help me with this? Thanks in advance.
You don't specify where the exception is thrown but a very common reason for this (my opinion) is that your query doesn't return any results (or rows).

i have this treeview for menu assignment. i want to know that can we find out if our rows have been updated. if yes then how?

the coding
foreach (TreeNode item in this.TreeView1.CheckedNodes)
{
if (item.Checked == true)
{
int strTreeValue = Convert.ToInt32(item.Value);
SqlCommand com = new SqlCommand("Update Role_Menu Set Role_id=('" + roleid + "')
Where Menu_id=('" + strTreeValue + "')", con);
com.ExecuteNonQuery();
da = new SqlDataAdapter(com);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables.Count == 0)
{
com = new SqlCommand("insert into Role_Menu(Role_id,Menu_id)
values('" + roleid + "','" + strTreeValue + "')", con);
com.ExecuteNonQuery();
}
}
in the above if(ds.tables.count == 0) i am trying to find if the rows have been updated or not but it is wrong and does not work. if a row is updated then how can we come to know it is updated and which one is updated.
You can use the code as follow
foreach (TreeNode item in this.TreeView1.CheckedNodes)
{
if (item.Checked == true)
{
int strTreeValue = Convert.ToInt32(item.Value);
SqlCommand com = new SqlCommand("Update Role_Menu Set Role_id=('" + roleid + "')
Where Menu_id=('" + strTreeValue + "')", con);
int i=com.ExecuteNonQuery();
if (i<= 0)
{
com = new SqlCommand("insert into Role_Menu(Role_id,Menu_id)
values('" + roleid + "','" + strTreeValue + "')", con);
com.ExecuteNonQuery();
}
}
Edit 1
You don't need to use SqlDataAdapter and DataSet
If you run the SQL from your question in a SqlCommand and check the return value of ExecuteNonQuery it should tell you how many records were affected.
From the documentation:
Return Value
Type: System.Int32
The number of rows affected.

ArgumentNull exception in asp.net web application

I have developed an asp.net application in which input will be given through an excel sheet.
This application is working fine in a system with WINDOWS XP and MS office 2008.
If i try to run the same application in a system with WINDOWS 7 and MS office 2010 i am getting a Argument Null Exception.
Code:
foreach (var dr in data)
{
LHSupdate = new LHSUpdate();
if (!string.IsNullOrEmpty(Convert.ToString(dr["Associate Id"])))
{
AssociateID = Convert.ToString(dr["Associate Id"]);
}
LHSupdate.AssciateID = AssociateID;
if (!string.IsNullOrEmpty(Convert.ToString(dr["Associate Name"])))
{
AssociateName = Convert.ToString(dr["Associate Name"]);
}
LHSupdate.Name = AssociateName;
var designation = dsData.Tables["LHS"].AsEnumerable().Where(r => Convert.ToString(r["Associate Id"]).Trim() == LHSupdate.AssciateID.Trim());
if (designation != null)
{
foreach (var de in designation)
{
LHSupdate.Designation = Convert.ToString(de["Level"]);
}
}
else
{
LHSupdate.Designation = "";
}
LHSupdate.CourseName = Convert.ToString(dr["Trainings "]);
LHSupdate.CourseStatus = Convert.ToString(dr["Training Status"]);
LHSupdate.Score = Convert.ToString(dr["Credits"]);
LHSupdate.LearningMode = Convert.ToString(dr["Venue"]);
LHSupdate.StartDate = Convert.ToString(dr["Start Date"]);
LHSupdate.EndDate = Convert.ToString(dr["End Date"]);
lstLHS.Add(LHSupdate);
}
I am getting error in the line:
var designation = dsData.Tables["LHS"].AsEnumerable().Where(r => Convert.ToString(r["Associate Id"]).Trim() == LHSupdate.AssciateID.Trim());
Code:
private DataSet Getdata()
{
string connectionString = "";
string getExcelSheetName = string.Empty;
if (fuLHSEntry.HasFile)
{
string fileName = Path.GetFileName(fuLHSEntry.PostedFile.FileName);
string fileExtension = Path.GetExtension(fuLHSEntry.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
fuLHSEntry.SaveAs(fileLocation);
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + #";Extended Properties=" + Convert.ToChar(34).ToString() + #"Excel 8.0;Imex=1;HDR=Yes;" + Convert.ToChar(34).ToString();
}
else if (fileExtension == ".xlsx" || fileExtension == ".xlsm")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + #";Extended Properties=" + Convert.ToChar(34).ToString() + #"Excel 12.0;IMEX=2;HDR=Yes;" + Convert.ToChar(34).ToString();
}
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
int count = 0;
foreach (DataRow dr in dtExcelSheetName.Rows)
{
getExcelSheetName = GetSheetName(dr);
if (!string.IsNullOrEmpty(getExcelSheetName))
{
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
if (getExcelSheetName.ToUpper().Contains("LEARNING"))
{
getExcelSheetName = "LEARNING";
}
else
{
getExcelSheetName = "LHS";
}
dAdapter.Fill(dsData, getExcelSheetName);
count++;
if (count == 2)
{
break;
}
}
}
con.Close();
}
return dsData;
}
Please help me in resolving this issue.
Thanks,
Raji
From your code it appears that the table can have two possible names.
Either give it always the same name that you're using later when reading:
dAdapter.Fill(dsData, "LHS");
Or you can take the table by index ignoring its name altogether:
var designation = dsData.Tables[0].AsEnumerable().Where(r => Convert.ToString(r["Associate Id"]).Trim() == LHSupdate.AssciateID.Trim());

Resources