Nested foreach() messing up - asp.net

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();
}
}
}

Related

Cascading for multiple selection of checkbox list

I want to retrieve data from oracle data base for one Checkbox list to another checkbox List for multiple selection in asp.net.
But unfortunately i am getting same ID again again while debugging.
Please help me Where i am doing mistake.
Is there any another easy approach on same.
I want something like : "Select d.depot_code, d.depot_description from table where d.depot in (depot_code from another Checkbox List) " [with comma separated ID]
CODE:
ddlregion Binding code:
public void BindRegion()
{
OracleCommand Cmd = new OracleCommand("select * from regions", con);
Cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = Cmd;
da.Fill(ds);
ddlregion.DataSource = ds;
ddlregion.DataTextField = "REGION_DESC";
ddlregion.DataValueField = "REGION_CODE";
ddlregion.DataBind();
}
protected void ddlregion_SelectedIndexChanged(object sender, EventArgs e)
{
ddlDepot.Items.Clear();
ddlDepot.Items.Add(new ListItem("--Select Depot--", ""));
for (int i = 0; i < ddlregion.Items.Count; i++)
{
if (ddlregion.Items[i].Selected == true)
{
string str = "select d.depot_code, d.depot_description from regions r, sub_regions sr, depots d where r.region_code = sr.region_code and sr.sub_region_code = d.sub_region_code and active = 'Y' and d.depot_code = " + ddlregion.SelectedItem.Value + "";
OracleCommand Cmd = new OracleCommand(str, con);
Cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = Cmd;
da.Fill(ds);
ddlDepot.DataSource = ds;
ddlDepot.DataTextField = "DEPOT_DESCRIPTION";
ddlDepot.DataValueField = "DEPOT_CODE";
ddlDepot.DataBind();
}
}
}
Thanks
Looking at your code again it doesn't look like you need to loop through your region dropdown list. In your ddlRegion_indexchanged just go ahead and bind your ddlDepot drop down and pass it the ddlregion.SelectedValue. So all you need is below, the ddlDepot will bind accordingly when you change the Region because you pass it the selected value every time.
string str = "select d.depot_code, d.depot_description from regions r, sub_regions sr, depots d where r.region_code = sr.region_code and sr.sub_region_code = d.sub_region_code and active = 'Y' and d.depot_code = " + ddlregion.SelectedValue + "";
OracleCommand Cmd = new OracleCommand(str, con);
Cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = Cmd;
da.Fill(ds);
ddlDepot.DataSource = ds;
ddlDepot.DataTextField = "DEPOT_DESCRIPTION";
ddlDepot.DataValueField = "DEPOT_CODE";
ddlDepot.DataBind();

How to create SelectIndexChanged event for multiple selection in asp.net

I want to select multiple item from checkbox list and then fill another check Box list on select index changed event of First check box list but after one selection its not working for another selected items because of "Auto Post Back = true" while debbuging i can see pointer start from page load event. I want after selection of all Item it should be fire "ddlregion_SelectedIndexChanged" so that I can able see all selected Item related value in another check Box List.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindRegion();
}
}
Due to this its not fetching data for another selected Items how to solve this issues Please help me.
ddlRegion Code Binding:
public void BindRegion()
{
OracleCommand Cmd = new OracleCommand("select * from regions", con);
Cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = Cmd;
da.Fill(ds);
ddlregion.DataSource = ds;
ddlregion.DataTextField = "REGION_DESC";
ddlregion.DataValueField = "REGION_CODE";
ddlregion.DataBind();
}
Select Index Changed Event
protected void ddlregion_SelectedIndexChanged(object sender, EventArgs e)
{
ddlDepot.Items.Clear();
ddlDepot.Items.Add(new ListItem("--Select Depot--", ""));
foreach (ListItem item in ddlregion.Items)
{
if (item.Selected == true)
{
string str = "select d.depot_code, d.depot_description from regions r, sub_regions sr, depots d where r.region_code = sr.region_code and sr.sub_region_code = d.sub_region_code and active = 'Y' and r.region_code in " + ddlregion.SelectedValue + "";
OracleCommand Cmd = new OracleCommand(str, con);
Cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = Cmd;
da.Fill(ds);
ddlDepot.DataSource = ds;
ddlDepot.DataTextField = "DEPOT_DESCRIPTION";
ddlDepot.DataValueField = "DEPOT_CODE";
ddlDepot.DataBind();
}
}
}
You need to build your region list for the SQL, then once done call your SQL and Bind.
string regions = "";
bool regionSelected = false;
foreach (ListItem item in ddlregion.Items)
{
if (item.Selected == true)
{
regions += item.SelectedValue + ",";
regionSelected = true;
}
}
// looping done so clean up string for SQL
regions = "(" + regions.TrimEnd(',') + " )";
//only run if a region is selected
if(regionSelected)
{
string str = "select d.depot_code, d.depot_description from regions r, sub_regions sr,
depots d where r.region_code = sr.region_code and
sr.sub_region_code = d.sub_region_code and active = 'Y' and r.region_code
in " + regions;
OracleCommand Cmd = new OracleCommand(str, con);
Cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = Cmd;
da.Fill(ds);
ddlDepot.DataSource = ds;
ddlDepot.DataTextField = "DEPOT_DESCRIPTION";
ddlDepot.DataValueField = "DEPOT_CODE";
ddlDepot.DataBind();
}

Avoiding PostBack in asp

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);
}
}
}
}
}

Placing DataBound Drop Down List into TableCell

I have a bound drop down list that I would like to place into a Table Cell. I am used to Labels and Text Boxes but I cannot seem to get the syntax working on this one. This code is inside of a Webmethod and my output has to be just the html. Thank you.
[System.Web.Services.WebMethod]
public static string gatherSurchargeData(string PriceListItemID, string ProdID, string ColorCode)
{
DataTable GetProductSizes = new DataTable();
GetProductSizes = DataLayer.PricingToolDL.getProductSizes(ProdID, ColorCode);
DataTable dt = new DataTable();
dt = DataLayer.PricingToolDL.getScharge(PriceListItemID);
Table tblScharges = new Table();
tblScharges.ID = "tblScharges";
TableHeaderRow th = new TableHeaderRow();
TableHeaderCell thSizeScharge = new TableHeaderCell();
thSizeScharge.Text = "Size";
th.Cells.Add(thSizeScharge);
tblScharges.Rows.Add(th);
int i = 0;
while (i <= dt.Rows.Count - 1)
{
TableRow tr = new TableRow();
tr.ID = "tableTr" + i;
TableCell tcSizeScharge = new TableCell();
DropDownList ddl = new DropDownList();
ddl.DataSource = GetProductSizes;
ddl.DataTextField = "FitSize";
ddl.DataValueField = "FitSize";
ddl.DataBind();
//string dtMovexSKU = dt.Rows[i]["MovexSKU"].ToString();
//DataRow[] GetProductSizesMovexSKU = GetProductSizes.Select("MovexSKU Like'" + dtMovexSKU + "'");
//tcSizeScharge.ID = "tcSizeScharge" + i;
//tcSizeScharge.Text = GetProductSizesMovexSKU[0][1].ToString();
tr.Cells.Add(tcSizeScharge);
tblScharges.Rows.Add(tr);
i++;
}
string html = "";
using (StringWriter sw = new StringWriter())
{
tblScharges.RenderControl(new HtmlTextWriter(sw));
html = sw.ToString();
}
return html;
}
The commented lines would be the code I would use if I were only wanting text to appear if that helps.
You need to add control in tablecell like this
tcSizeScharge.Controls.Add(ddl);

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.

Resources