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 bridge_Default3 : 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 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##

 


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 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

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 May 27, 2009 16:08

Since I started posting my code snippets and samples I've not been happy with the formatting. Code is never easy to understand even less so when the syntax isn't highlighted. I went on a google and found the following site: http://www.manoli.net/csharpformat/. It allows you to format your C#, VB, HTML, XML, T-SQL or MSH (code name Monad) code for publishing on a web site or in a blog, highlighting the syntax.

It would be nice if I could write some function to do this for me when I blog but tI think that may be some time in coming! In the meantime I shall be using this tool to make my code sample and snipets easier on the eye.

Also I've jsut decided that leaving the line numbers out will be better as then the code and just be copied out, with the line numbers you can't do a straight copy and paste.


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Beanie posted on May 27, 2009 09:29

For a while I'd heard about webservices and thought that they could be useful, when an idea came up at work to provide remote services to clients i thought I'd better find out how it all worked.

First of all I wrote my own web service; http://beanengineering.co.uk/webservices/webservice.asmx, its very simple and has two functions one returns the words "Hello World"and the other returns 10 * 3. I know that they are of no real use to anyone but I needed a simple starting point, from here I could then get to grips with using the remote functions.

First of all we need to reference the webservice, this is done in the web.config file (you can also use the add web reference wizard of Visual Studio).

web.config

<appSettings>
<add key="beanengineering.webservice" value="http://beanengineering.co.uk/webservices/webservice.asmx"/>
</appSettings>

The we have a couple of labels to display the results.

webservice.aspx

<asp:Label ID="lblHelloWord" runat="server" Text=""></asp:Label>
<asp:Label ID="lblIntTest" runat="server" Text=""></asp:Label>

Finally the code to run the functions.

webservice.aspx.cs

   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:   
   8:  public partial class webservice : System.Web.UI.Page
   9:  {
  10:      protected void Page_Load(object sender, EventArgs e)
  11:      {
  12:          uk.co.beanengineering.WebService ws = new uk.co.beanengineering.WebService();
  13:          lblHelloWord.Text = ws.HelloWorld().ToString();
  14:          lblIntTest.Text = ws.TestInt().ToString();
  15:      }
  16:  }

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Beanie posted on May 1, 2009 16:28
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Text;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
public partial class textgif : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Load the Image to be written on.
Bitmap bitMapImage = new System.Drawing.Bitmap(Server.MapPath("gen_img.jpg"));
Graphics graphicImage = Graphics.FromImage( bitMapImage );
//Smooth graphics is nice.
graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
//Write your text.
SolidBrush oBrushWrite = new SolidBrush(Color.Navy);
graphicImage.DrawString("Welcome to BeanEngineering",
new Font("Arial", 22, FontStyle.Italic),
oBrushWrite, new Point(0, 0));
//Set the content type
Response.ContentType = "image/gif";
//Save the new image to the response output stream.
bitMapImage.Save(Response.OutputStream, ImageFormat.Gif);
//Clean house.
graphicImage.Dispose();
bitMapImage.Dispose();
}
}

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 February 25, 2009 09:47

This is a function to make a string into title case ie every word has a capital letter to start.  

More...


Be the first to rate this post

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

Page List

Search Blog

Tag Cloud

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

© Copyright 2010 Beanie