DataTable dt = new DataTable(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindRepeater(); RepeaterMenu.DataSource = dt; RepeaterMenu.DataBind(); } } public DataTable BindRepeater() { dt = new Select() .From<CmsMenu>() .Where(CmsMenu.PublishedColumn) .IsEqualTo(true) .And(CmsMenu.FooterMenuColumn) .IsEqualTo(true) .OrderAsc("sortOrder") .ExecuteDataSet().Tables[0]; return dt; }
Archive for the Category » C# «
Always forgetting this one!
int sortOrder;//a sort order has been entered if (Int32.TryParse(txtSortOrder.Text, out sortOrder)) { } else { sortOrder = 0; }
I have spent the last day trying to find a solution to what turns out to be a very common problem with the ASP.NET treeview control. Basically, I am pulling my data out of SQL and binding it to my treeview to use as navigation through a series of categories. My problem was that when I click a category (i’m redirecting to another page based on the category selected) the treeview loses all state and loads a fresh. Oh, my treeview control is in a user control btw, not in a master page.
The solution I came up with (couldn’t find a solution on the web that would work for me, i looked at the recursion method among many others, but for whatever reason it wouldn’t work. Maybe because the control is a user control and not directly within a master page??) is rather a simple one, but it works! I’m sure there maybe more efficient and better ways of doing it, but like I said, this one works for me!
So this is what I do…
When a node is clicked I get the valuepath of the node via the SelectedNodeChanged event. I store this value in a session variable. When the resultant page loads I then use the OnPreRender method which is, and I quote;
"The PreRender event is raised just before the page is about to render its
contents. This is the last chance to modify a page output before it is sent
to the browser".
In this method I check to see if the session for the valuepath has any data. If it does I check to see if it has a separator. If there is that means we are more than one level deep into our treeview else if not, we are at the root level. If we are more than one level deep I throw the value into an array. I then basically loop through the array writing out the TreeView1.Findnode method as I go. So we are left with something like this;
TreeView1.FindNode("6").Expand();
TreeView1.FindNode("6/11").Expand();
TreeView1.FindNode("6/11/15").Expand();
That’s basically it. The code is below.
ASP.NET
<asp:TreeView ID="TreeView1" NodeWrap="true" ExpandDepth="0" runat="server" OnTreeNodePopulate="TreeView1_TreeNodePopulate" PathSeparator="/" ImageSet="MSDN" CssClass="categoryMenu" OnDataBound="TreeView1_DataBound" OnSelectedNodeChanged="TreeView1_SelectedNodeChanged" ShowCheckBoxes="None" SelectedNodeStyle-CssClass="categorySelected"> <ParentNodeStyle Font-Bold="False" CssClass="navigationLink" /> <HoverNodeStyle Font-Underline="True" ForeColor="" /> <NodeStyle NodeSpacing="0px" VerticalPadding="0px" /></asp:TreeView>
C#
protected override void OnPreRender(EventArgs e) { if (Session["SelectedNodeValuePath"] != null) { //the selected node value is something like 6/11 string nodeValuePath = Session["SelectedNodeValuePath"].ToString(); //get the position of the first / int firstSeparator = nodeValuePath.IndexOf("/"); if (nodeValuePath.IndexOf("/") > 0) { //define the character that separates char[] separator = { '/' }; //split the string string[] array = nodeValuePath.Split(separator); StringBuilder path = new StringBuilder(); int noArrayElements = array.Length; // if you select the third node down in a tree, the array will write out the following // TreeView1.FindNode("6").Expand(); // TreeView1.FindNode("6/11").Expand(); // TreeView1.FindNode("6/11/15").Expand(); for (int i = 1; i < array.Length; i++) { // if there is only one element in my array there is then only 1 node to expand. if (noArrayElements == 1) { path.Append(array[i - 1]); TreeView1.FindNode(path.ToString()).Expand(); } // if there is more than one element i need to add the separator to the node path and then expand the node if (noArrayElements > 1) { if (i == 1) { // don't prefix searator if first node path.Append(array[i - 1]); TreeView1.FindNode(path.ToString()).Expand(); } else { // prefix separator for subsequent nodes path.Append("/"); path.Append(array[i - 1]); TreeView1.FindNode(path.ToString()).Expand(); } } } } TreeView1.FindNode(Session["SelectedNodeValuePath"].ToString()).Select(); } }protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e) { //Get the value of the selected node int catID; catID = Convert.ToInt32(TreeView1.SelectedValue); string valuePath = TreeView1.SelectedNode.ValuePath; Session["selectedValue"] = catID; Session["SelectedNodeValuePath"] = valuePath; //Get the name of the selected category Category c = new Category(catID); string itemUrl = c.CatName; //pass the name through our clean URL class for URLrewriting itemUrl = CleanURLRewrite.cleanURL(itemUrl); //Check if we're rewriting urls and redirect accordingly if (System.Convert.ToBoolean((ConfigurationManager.AppSettings["EnableURLrewrite"])) == true) { Response.Redirect(ConfigurationManager.AppSettings["cartDirectory"].ToString() + "cat/" + catID + "/" + itemUrl + ".aspx", false); } else { Response.Redirect(ConfigurationManager.AppSettings["cartDirectory"].ToString() + "Items.aspx?category=" + catID.ToString(), false); } }
Sort and page the results
public SortDirection SortDir { get { if (ViewState["sortDirection"] == null) { ViewState["sortDirection"] = SortDirection.Ascending; } return (SortDirection)ViewState["sortDirection"]; } set { ViewState["sortDirection"] = value; } } DataSet ds = new DataSet(); DataView dv = new DataView(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindGrid(); GridView1.DataSource = dv; GridView1.DataBind(); } } private DataView BindGrid() { ds = new Query(AnthemWeb.DAL.Item.Schema).ExecuteDataSet(); if (ViewState["sortExpr"] != null) { dv = new DataView(ds.Tables[0]); dv.Sort = (string)ViewState["sortExpr"]; } else { dv = ds.Tables[0].DefaultView; } return dv; } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; GridView1.DataSource = BindGrid(); GridView1.DataBind(); } protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) { string stExp = e.SortExpression; string stDir = string.Empty; if (SortDir == SortDirection.Ascending) { SortDir = SortDirection.Descending; stDir = "DESC"; } else { SortDir = SortDirection.Ascending; stDir = "ASC"; } ViewState["sortExpr"] = e.SortExpression + " " + stDir; GridView1.DataSource = BindGrid(); GridView1.DataBind(); } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { int selectedRowIndex; selectedRowIndex = GridView1.SelectedIndex; GridViewRow row = GridView1.Rows[selectedRowIndex]; string ID = row.Cells[0].Text; Response.Redirect("customer-details.aspx?ID=" + ID, false); } protected void btnSearch_Click(object sender, EventArgs e) { BindGrid(); }
Started this week to use Subsonic to generate my DAL. I got this handy reference from their forum for doing the INSERTS etc…
private void BindNames()
{
AddBook.DLL.AddressBookCollection list = new AddBook.DLL.AddressBookCollection().OrderByAsc("Name").Load();
this.ddNames.DataSource = list;
this.ddNames.DataTextField = "Name";
this.ddNames.DataValueField = "UserID";
this.ddNames.DataBind();
}
protected void btnSelect_Click(object sender, EventArgs e)
{
AddBook.DLL.AddressBook ab = new AddBook.DLL.AddressBook(ddNames.SelectedValue);
this.tbName.Text = ab.Name;
this.tbSurname.Text = ab.Surname;
this.tbAddress.Text = ab.Address;
this.tbHomePhone.Text = ab.HomePhone;
this.tbMobilePhone.Text = ab.MobilePhone;
}protected void btnDelete_Click(object sender, EventArgs e)
{
AddBook.DLL.AddressBook ab = new AddBook.DLL.AddressBook(ddNames.SelectedValue);
AddBook.DLL.AddressBook.Delete(ab.UserID);
BindNames();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
AddBook.DLL.AddressBook ab = new AddBook.DLL.AddressBook(ddNames.SelectedValue);
ab.Name = tbName.Text;
ab.Surname = tbSurname.Text;
ab.Address = tbAddress.Text;
ab.HomePhone = tbHomePhone.Text;
ab.MobilePhone = tbMobilePhone.Text;
ab.Save();
BindNames();
}protected void btnInsert_Click(object sender, EventArgs e)
{
AddBook.DLL.AddressBook ab = new AddBook.DLL.AddressBook();
ab.Name = tbName.Text;
ab.Surname = tbSurname.Text;
ab.Address = tbAddress.Text;
ab.HomePhone = tbHomePhone.Text;
ab.MobilePhone = tbMobilePhone.Text;
ab.Save();
BindNames();
}
Example page = www.mysite.com/pickup-golding.aspx
C# code
string loadedPageName = Path.GetFileName(Page.Request.PhysicalPath); Response.Write(loadedPageName);
Result = pickup-golding.aspx
The XML File
<client_order ordID="14" supplierID="000002"> <item_order itoItemID="12" itoItemQty="1" itoItemPrice="35.99" itoTaxAmount="3.00" itemCode="LD3162" /> <item_order itoItemID="3" itoItemQty="0" itoItemPrice="29.99" itoTaxAmount="3.00" itemCode="LD3278" /> <item_order itoItemID="7" itoItemQty="0" itoItemPrice="31.99" itoTaxAmount="3.00" itemCode="LD3226" /> <item_order itoItemID="10" itoItemQty="0" itoItemPrice="31.99" itoTaxAmount="3.00" itemCode="LD3226" /> <item_order itoItemID="9" itoItemQty="0" itoItemPrice="29.99" itoTaxAmount="3.00" itemCode="LD3226" /> </client_order>
The CODE ;o)
//Get the XML string responseXML = r["Response"].ToString(); try { XmlDocument contentXML = new XmlDocument(); contentXML.LoadXml(responseXML); //Get the attribute values from the root node <client_order> XmlNode client_orderNode = contentXML.DocumentElement.SelectSingleNode("//client_order"); string supplierID = client_orderNode.Attributes["supplierID"].Value.ToString(); string ordID = client_orderNode.Attributes["ordID"].Value.ToString(); string supplierName = CommonDBCommands.SelectValue(connectionString, "suppliers", "supplierName", "supplierID", supplierID); //GET the order id and supplier as recorded in the XML response. Debug.Print("Supplier ID = " + supplierID); Debug.Print("Order ID = " + ordID); //read each element <item_order> in <client_order> and get the attribute values foreach (XmlNode node in client_orderNode) { XmlElement item_order = (XmlElement)node; string itemID = ""; string itemQty = ""; string itemPrice = ""; string itemTaxAmount = ""; string itemCode = ""; if (item_order.HasAttributes) { itemID = item_order.Attributes["itoItemID"].InnerText; itemQty = item_order.Attributes["itoItemQty"].InnerText; itemPrice = item_order.Attributes["itoItemPrice"].InnerText; itemTaxAmount = item_order.Attributes["itoTaxAmount"].InnerText; itemCode = item_order.Attributes["itemCode"].InnerText; if (itemID == hItemID) { DataRow row = dt.NewRow(); row["SupplierName"] = supplierName; row["itemID"] = itemID; row["Qty"] = Convert.ToDecimal(itemQty); row["price"] = Convert.ToDecimal(itemPrice); row["taxAmount"] = Convert.ToDecimal(itemTaxAmount); row["itemCode"] = itemCode; dt.Rows.Add(row); } } Debug.Print("item ID = " + itemID); Debug.Print("price = $" + itemPrice); } } catch (Exception ex) { Response.Write(ex.Message.ToString()); }
protected void LogOut() { Session.Abandon(); string nextpage = "Logoutt.aspx"; Response.Write("<script language=javascript>"); Response.Write("{"); Response.Write(" var Backlen=history.length;"); Response.Write(" history.go(-Backlen);"); Response.Write(" window.location.href='" + nextpage + "'; "); Response.Write("}"); Response.Write("</script>"); }
The aspx page
<asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="btnTemplate" runat="server" OnClick="btnTemplate_Click">LinkButton</asp:LinkButton> </ItemTemplate> </asp:TemplateField>
The C# code behind
protected void btnTemplate_Click(object sender, EventArgs e) { //Clear Selection GridView1.SelectedIndex = -1; // Get the checkbox that was Selected LinkButton btnTemplate = (LinkButton)sender; // As this is a template column, we can get the specifc row by using the Naming Container GridViewRow selectedGridRow = (GridViewRow)btnTemplate.NamingContainer; // get the userID from the first column that is hidden by CSS Response.Write(selectedGridRow.Cells[0].Text); }
