Beanie posted on December 8, 2009 08:47

I needed to display a list, countries in this case, over two columns. It is relatively simple using record set paging, in its simplest form you count the total rows divide by the number of columns you want then set the page size to the result of that calculation. Then instead of button to scroll through the record set we have a repeater for each page – simples ;-).

ASPX

   1:  <div id="CountryList1" style="float:left; width:40%">
   2:      <asp:Repeater ID="rptCountryList1" runat="server">
   3:          <ItemTemplate>
   4:              <li>
   5:                  <a href="Description.aspx?country=<%# DataBinder.Eval(Container.DataItem, "fldCountryID") %>">
   6:                      <%# DataBinder.Eval(Container.DataItem, "fldCountry") %>
   7:                  </a>
   8:              </li>
   9:          </ItemTemplate>
  10:      </asp:Repeater>
  11:  </div>
  12:   
  13:  <div id="CountryList2" style="float:left; width:40%">
  14:      <asp:Repeater ID="rptCountryList2" runat="server">
  15:          <ItemTemplate>
  16:              <li>
  17:                  <a href="Description.aspx?country=<%# DataBinder.Eval(Container.DataItem, "fldCountryID") %>">
  18:                      <%# DataBinder.Eval(Container.DataItem, "fldCountry") %>
  19:                  </a>
  20:              </li>
  21:          </ItemTemplate>
  22:      </asp:Repeater>
  23:  </div>

 

Code behind

   1:  using System;
   2:  using System.Web;
   3:  using System.Web.Security;
   4:  using System.Web.UI;
   5:  using System.Web.UI.WebControls;
   6:  using System.Web.UI.WebControls.WebParts;
   7:  using System.Web.UI.HtmlControls;
   8:  using System.Data.SqlClient;
   9:  using System.Data;
  10:  using System.Configuration;
  11:   
  12:  public partial class page_name : System.Web.UI.Page
  13:  {
  14:      SqlConnection scon=new  SqlConnection(ConfigurationManager.AppSettings["strConn"]);
  15:      SqlDataAdapter sDA;
  16:      DataSet dsCountryList1;
  17:      DataSet dsCountryList2;
  18:   
  19:      const int intPages = 2;
  20:      int intRows;
  21:      int rowSum;
  22:   
  23:      private void BindData()
  24:      {
  25:          rptCountryList1.DataSource = dsCountryList1;
  26:          rptCountryList1.DataBind();
  27:          rptCountryList2.DataSource = dsCountryList2;
  28:          rptCountryList2.DataBind();
  29:      }
  30:   
  31:      private void readpage(int n)
  32:      {
  33:          SqlCommand cmd = new SqlCommand("SelectCountriesByLetter", scon);
  34:          cmd.CommandType = CommandType.StoredProcedure;
  35:          cmd.Parameters.Add(new SqlParameter("@Product", 10));
  36:          cmd.Parameters.Add(new SqlParameter("@Letter", "%"));
  37:          sDA = new SqlDataAdapter(cmd);
  38:          dsCountryList1 = new DataSet();
  39:          dsCountryList1.Clear();
  40:          sDA.Fill(dsCountryList1, 0, intRows, "tblCountry");
  41:          dsCountryList2 = new DataSet();
  42:          dsCountryList2.Clear();
  43:          sDA.Fill(dsCountryList2,  intRows, intRows, "tblCountry");
  44:      }
  45:   
  46:      protected void Page_Load(object sender, EventArgs e)
  47:      {
  48:          if (!Page.IsPostBack)
  49:          {
  50:              SqlCommand cmd = new SqlCommand("SelectCountriesByLetter", scon);
  51:              cmd.CommandType = CommandType.StoredProcedure;
  52:              cmd.Parameters.Add(new SqlParameter("@Product", 10));
  53:              cmd.Parameters.Add(new SqlParameter("@Letter", "%"));
  54:              sDA = new SqlDataAdapter(cmd); 
  55:              dsCountryList1 = new DataSet();
  56:              try
  57:              {
  58:                  sDA.Fill(dsCountryList1, "tblCountry");
  59:                  rowSum = dsCountryList1.Tables[0].Rows.Count;
  60:              }
  61:              catch (Exception ex)
  62:              {
  63:                  rowSum = 0;
  64:                  return;
  65:              }
  66:              intRows = rowSum / intPages;
  67:              readpage(1);
  68:              BindData();     
  69:          }
  70:      }
  71:  } 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Beanie posted on November 25, 2009 15:31

Ever needed to display more than one value in a bulleted list or dropdown, I did and here is how I ended up getting round it.

Using a normal bulleted list, we leave of the data source and on pageload run loadBulletedLists passing in the list and any variables to filter the stored stocedure used to populate it.

loadBulletedLists takes the recordset and inserts the results into the list, if there are two columns in a row is adds both seperated by a comma, if not it adds the one column.

aspx page

<asp:BulletedList ID="blBulletedList" runat="server" EnableViewState="True"></asp:BulletedList>
aspx.cs page
   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Web;
   5:  using System.Web.UI;
   6:  using System.Web.UI.WebControls;
   7:  using System.Data;
   8:  using System.Data.SqlClient;
   9:  using System.Configuration;
  10:  public partial class Default : System.Web.UI.Page
  11:  {
  12:      protected void Page_Load(object sender, EventArgs e)
  13:      {
  14:          if (!IsPostBack)
  15:          {
  16:              loadBulletedLists(blBulletedList,0);
  17:          }
  18:      }
  19:      protected void loadBulletedLists(object sender, object vParameter)
  20:      {
  21:          BulletedList blList = ((BulletedList)sender);
  22:          blList.Items.Clear();
  23:   
  24:          SqlConnection conn = null;
  25:          conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
  26:          SqlDataReader rdr = null;
  27:          
  28:          conn.Open();
  29:          SqlCommand cmd = new SqlCommand("selectBulletedListItems", conn);
  30:          cmd.CommandType = CommandType.StoredProcedure;
  31:          cmd.Parameters.Add(new SqlParameter("@Parameter", vParameter));
  32:   
  33:          string strColumn1;
  34:          string strColumn2;
  35:          rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  36:          string strTitle = "";
  37:   
  38:          while (rdr.Read())
  39:          {
  40:              strColumn1 = rdr["fldColumn1"].ToString();
  41:              strColumn2 = rdr["fldColumn2"].ToString();
  42:              if (strColumn1 != "")
  43:              {
  44:                  strTitle = strColumn1;
  45:              }
  46:              if (strColumn2 != "")
  47:              {
  48:                  if (strTitle != "")
  49:                  {
  50:                      strTitle += ", " + strColumn2;
  51:                  }
  52:                  else
  53:                  {
  54:                      strTitle = strColumn2;
  55:                  }
  56:              }
  57:              blList.Items.Add(new ListItem(strTitle));
  58:          }
  59:      }
  60:  }

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Beanie posted on October 27, 2009 18:49
   1:  protected void cboCountry_SelectedIndexChanged(object sender, EventArgs e)
   2:  {        
   3:      cboState.DataBind();
   4:      if (cboState.Items.Count != 0)
   5:      {
   6:          cboState.Visible = true;
   7:          ListItem li = new ListItem("No State", "0");
   8:          cboState.Items.Add(li);
   9:          cboState.SelectedIndex = cboState.Items.IndexOf(cboState.Items.FindByValue("0"));
  10:      }
  11:      else
  12:      {
  13:          cboState.Visible = false;
  14:      }
  15:  }

Posted in: Development , Development - ASP  Tags: , , ,

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Beanie posted on September 9, 2009 08:56

Ever need to have a dropdown which allows you to have a SelectedIndex that's not in the list?

This is how to write a control to allow you to do this.

   1:  using System;
   2:  using System.Collections;
   3:  using System.Data;
   4:  using System.Web.UI.WebControls;
   5:  using System.Web.UI;
   6:  using System.ComponentModel;
   7:  namespace Controls {
   8:  public class ForgivingDropDownList : DropDownList
   9:      {
  10:          [Category("Behavior"), DefaultValue(true)]
  11:          public bool AllowInvalidSelectedValue
  12:          {
  13:              get { return ViewState["allowInvalid"] != null ? (bool)ViewState["allowInvalid"] : true; }
  14:              set { ViewState["allowInvalid"] = value; }
  15:          }
  16:   
  17:          public override string SelectedValue
  18:          {
  19:              get
  20:              {
  21:                  return base.SelectedValue;
  22:              }
  23:              set
  24:              {
  25:                  if (!AllowInvalidSelectedValue)
  26:                  {
  27:                      base.SelectedValue = value;
  28:                      return;
  29:                  }
  30:                  if (this.Items.Count != 0)
  31:                  {
  32:                      if ((value == null) || (base.DesignMode && (value.Length == 0)))
  33:                      {
  34:                          this.ClearSelection();
  35:                          return;
  36:                      }
  37:                      ListItem item = this.Items.FindByValue(value);
  38:                      if (item == null)
  39:                      {
  40:                          base.SelectedValue = null;
  41:                          return;
  42:                      }
  43:                      base.SelectedValue = value;
  44:                  }
  45:              }
  46:          }
  47:      }
  48:  }

Register it in web.config

   1:  <pages>
   2:         <controls>
   3:          <add tagPrefix="custom"  namespace="Controls" />
   4:      </controls>
   5:  </pages>

Using the dropdown

   1:  <Custom:ForgivingDropDownList  AppendDataBoundItems="true" ID="cbo" runat="server"  DataSourceID="dse" DataValueField="fldID" DataTextField="fld" SelectedValue='<%# bind("fldID") %>' >
   2:  </Custom:ForgivingDropDownList>
   3:                     

Simples ;-)


Posted in: Development  Tags: , , ,

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Beanie posted on September 6, 2009 16:22
Here we take the information from a contact form and email it to the site owner.

 

   1:  protected void btnSend_Click(object sender, EventArgs e)
   2:  {
   3:      if (Page.IsValid)
   4:      {
   5:          string fileName = Server.MapPath("ContactForm.txt");
   6:          string mailBody = string.Empty;
   7:          if (Cache["ContactFormMailBody"] == null)
   8:          {
   9:              mailBody = System.IO.File.ReadAllText(fileName);
  10:              Cache.Insert("ContactFormMailBody", mailBody, new CacheDependency(fileName));
  11:          }
  12:          else
  13:          {
  14:              mailBody = Cache["ContactFormMailBody"].ToString() + "\r\n(File from the cache)";
  15:          }
  16:   
  17:          mailBody = mailBody.Replace("##Name##", txtName.Text);
  18:          mailBody = mailBody.Replace("##Email##", txtEmailAddress.Text);
  19:          mailBody = mailBody.Replace("##HomePhone##", txtPhoneHome.Text);
  20:          mailBody = mailBody.Replace("##BusinessPhone##", txtPhoneBusiness.Text);
  21:          mailBody = mailBody.Replace("##Comments##", txtComments.Text);
  22:   
  23:          MailMessage myMessage = new MailMessage();
  24:          myMessage.Subject = "Response from web site";
  25:          myMessage.Body = mailBody;
  26:   
  27:          myMessage.From = new MailAddress("email@doamin.ext");
  28:          myMessage.To.Add(new MailAddress("web@doamin.ext"));
  29:          lblMessage.Text = "Your message has been sent to us";
  30:          SmtpClient mySmtpClient = new SmtpClient();
  31:          try
  32:          {
  33:              mySmtpClient.Send(myMessage);            
  34:          }
  35:          catch (Exception )
  36:          {
  37:              lblMessage.Text = "An error occurred while sending your e-mail. Please try again.";
  38:          }
  39:   
  40:          lblMessage.Visible = true;
  41:          FormTable.Visible = false;
  42:          System.Threading.Thread.Sleep(5000);
  43:      }
  44:  }
  45:   

The template

    Hi there,
A user has left the following feedback at the site:
Name:               ##Name##
E-mail address:     ##Email##
Home phone:         ##HomePhone##
Business phone:     ##BusinessPhone##
Comments:           ##Comments##

 


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Beanie posted on September 6, 2009 16:16

 How to run through all the files within a folder and list them in code.

List files to bulleted list

In this case we find all the files within the current folder except csharp.aspx and populate a bulleted list with them as hyperlinks. The C Sharp index file uses this code to create the sample list.

   1:  using System.IO; 
   2:  using System.Text.RegularExpressions;
   3:   
   4:  protected void Page_Load(object sender, EventArgs e)
   5:  {
   6:      DirectoryInfo di = new DirectoryInfo(MapPath(""));
   7:      FileInfo[] rgFiles = di.GetFiles("*.aspx");        
   8:      string strFile = "";
   9:      foreach (FileInfo fi in rgFiles)
  10:      {
  11:          if (fi.Name.ToLower() != "csharp.aspx")
  12:          {
  13:          strFile = Regex.Replace(fi.Name.ToLower(), ".aspx", "");
  14:          blCsharp.Items.Add(new ListItem(strFile,fi.Name.ToLower()));            
  15:          }
  16:      }
  17:  }

 

List files in dropdown list

In this case we list the number contained within a filename starting with a certain country name. The images/chart fodler contains many charts for different countries each with a numerical identifier As we only need the numberical identifier to store in a database we strip out the rest of the filename and list the charts as [chart #]

   1:  using System.IO;
   2:  using System.Text.RegularExpressions;
   3:   
   4:  protected void Page_Load(object sender, EventArgs e)
   5:  {
   6:      string strCountry = "country name";
   7:      string strChart = "";
   8:      DirectoryInfo di = new DirectoryInfo(MapPath("~/images/charts"));
   9:      FileInfo[] rgFiles = di.GetFiles(strCountry + "*.gif");
  10:      var slSortedList = new SortedList();
  11:   
  12:      foreach (FileInfo fi in rgFiles)
  13:      {
  14:          strChart = Regex.Replace(fi.Name.ToLower(), ".gif", "");
  15:          strChart = Regex.Replace(strChart, strCountry, "");
  16:          slSortedList.Add(strChart,"Chart " + strChart );
  17:      } 
  18:       cboChart.DataSource = slSortedList;
  19:       cboChart.DataTextField = "Value";
  20:       cboChart.DataValueField = "Key";
  21:       cboChart.DataBind();
  22:  }

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Beanie posted on September 6, 2009 16:14

A handy built in function of MS SQL that changes the owner of a table or object, simply fill in the table or object name and the name of the new user and execute it.

sp_changeobjectowner  'object' ,  'owner'    

Posted in: Development  Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Beanie posted on July 9, 2009 09:07

Simple expanding menu using style sheets, this menu expands on hover of the parent menu item. This version only works in Firefox and IE 7 and later (might work in safari and Chrome but I've not tested it) 

CSS

   1:  <style>
   2:      .menu li ul,.menu li:hover ul li ul
   3:      {
   4:          display: none;
   5:          list-style-type: none;
   6:      }
   7:   
   8:      .menu li:hover ul,.menu li:hover ul li:hover ul
   9:      {    
  10:          display: list-item;
  11:      }
  12:  </style>

HTML

   1:  <ul class="menu">
   2:      <li>menu 1
   3:          <ul>
   4:              <li>sub menu 11
   5:                  <ul>
   6:                      <li>sub sub menu 11</li>
   7:                      <li>sub sub menu 11</li>
   8:                  </ul>
   9:              </li>
  10:              <li>sub menu 12
  11:                  <ul>
  12:                      <li>sub sub menu 12</li>
  13:                      <li>sub sub menu 12</li>
  14:                  </ul>
  15:              </li>
  16:          </ul>
  17:      </li>
  18:      <li>menu 2
  19:          <ul>
  20:              <li>sub menu 2</li>
  21:              <li>sub menu 2</li>
  22:          </ul>
  23:      </li>
  24:      <li>menu 3
  25:          <ul>
  26:              <li>sub menu 3</li>
  27:              <li>sub menu 3</li>
  28:          </ul>
  29:      </li>
  30:    </ul>

The sub menus only display when you hover over the parent which does make it a bit clunky, the principles can be used to make a smoother operating menu either with javascript or using classed HTML.

How it works

It is a really simple use of style sheet, all it does is not display the sub list item unless there parent has the pseudo class hover. The hide is done by: "display: none;" and the reveal by: "display: list-item;". It really is that simple and that is the beauty of it.

 


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

This has to be the most annoying error that you can get, you have all your arguments lined up you know that the inputs for your stored procedure match the fileds from you gridview but still it errors.

Well finally I found out why I get this error, it's all to do with my typing or lack of it.

If I have my gridview populating from the a stored procedure which runs something like this:

Select

CREATE PROCEDURE SelectTable1
AS
SELECT field1, field2, field3, id 
FROM table1 

Update

   1:  CREATE PROCEDURE UpdateTable1
   2:  @field1 varchar(10) = null,
   3:  @feild2 varchar(10) = null,
   4:  @field3 varchar(10) = null,
   5:  @id int
   6:  AS
   7:  UPDATE table1
   8:  SET field1 = @field1, field2 = @feild2, field3 = @field3, 
   9:  WHERE id = @id

Grid View 

   1:  <asp:GridView ID="GridView1" runat="server" runat="server" AllowPaging="True" AllowSorting="True" 
   2:              AutoGenerateColumns="False" DataKeyNames="ID" 
   3:              DataSourceID="DataSource1" PageSize="20" AutoGenerateEditButton="True">
   4:      <Columns>        
   5:          <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" /> 
   6:          <asp:BoundField DataField="field1" HeaderText="field1" SortExpression="field1" /> 
   7:          <asp:BoundField DataField="field2" HeaderText="field2" SortExpression="field2" /> 
   8:          <asp:BoundField DataField="field3" HeaderText="field3" SortExpression="field3" />                  
   9:      </Columns>
  10:  </asp:GridView>

 Data Source

   1:  <asp:SqlDataSource ID="DataSource1" runat="server"ConnectionString="<%$ ConnectionStrings:strConnectionString %>" 
   2:          SelectCommand="selectTable1" SelectCommandType="StoredProcedure" UpdateCommand="UpdateTable1" UpdateCommandType="StoredProcedure">
   3:          <SelectParameters>
   4:          </SelectParameters>
   5:          <UpdateParameters>
   6:              <asp:Parameter DefaultValue="0" Name="ID" Type="Int32" />
   7:              <asp:Parameter DefaultValue="" Name="field1" Type="String" />
   8:              <asp:Parameter DefaultValue="" Name="field2" Type="String" />
   9:              <asp:Parameter DefaultValue="" Name="field3" Type="String" />
  10:          </UpdateParameters>
  11:  </asp:SqlDataSource>

So if you were to create this code inclueding the tables and data connections and tried to run the update you would get the following error "Procedure or function UpdateTable1 has too many arguments specified", looking at the code it all lines up. The stored procedure orks fine on it's own the select works the right arguments are being passed over, so what is the problem?

Well the problem lies in this case with field2 or feild2 aas the variable in the stored procedure is that slight typo causes the error, so if you get the error to many arguments check that your variables amtch with your selected fieldnames.


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Beanie posted on June 10, 2009 15:37

This code puts a time date stamp on a row in excel. All you need to do is put the code below in the worksheet code view of the worksheet you want to date stamp.

How it works:

Line 3 checks for column 1 (in this case) being change, you can set this to any column(s) you like, just not the same one as you date stamp.

Line 5 puts the date in the column 1 along (in this case) from the edited column

   1:  Private Sub Worksheet_Change(ByVal Target As Range)
   2:  On Error Resume Next
   3:      If Target.Column = 1 Then
   4:          Application.EnableEvents = False
   5:          Target.Offset.Offset(0, 1) = Now()
   6:          Application.EnableEvents = True
   7:      End If
   8:  End Sub

That should have it working, you might need to make sure the format of the column is correct to show the date in the right format and that the column is big enough to show it.


Posted in: Development  Tags: , ,

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Page List

Search Blog

Tag Cloud

Recent Comments

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012 Beanie