UAD8: Query String Builder

Ever had controls that need to add to the Query String but not duplicate or erase what’s already there? This is a little utility I dug out and just changed to use a generic dictionary recently. Just use it as you would a normal dictionary. When you instantiate a copy it picks up the current query string. There are two ToString() methods, one just return the query string and the other appends another string to the end and takes care of the ? & issues.

public class QueryStringBuilder : Dictionary<String,String>
{
 
	public QueryStringBuilder()
	{
		//not very effecient, but I'll find a better way one day
		foreach (String key in HttpContext.Current.Request.QueryString.AllKeys)
		{
			Add(key, HttpContext.Current.Request.QueryString[key]);
		}
	}
	public void Add(String key, String value){
		if (base.ContainsKey(key))
		{
			base[key] = value;
		}
		else base.Add(key, value);
	}
	public void Remove(String key)
	{
		if (base.ContainsKey(key))
		{
			base.Remove(key);
		}
	}
 
	public override string ToString()
	{
		StringBuilder sb = new StringBuilder();
		bool start = true;
		foreach (String s in base.Keys)
		{
			sb.Append((start ? "?" : "&") + s + "=" + HttpContext.Current.Server.UrlEncode(base[s]));
			start = false;
		}
		return sb.ToString();
	}
	public string ToString(string append)
	{
		StringBuilder sb = new StringBuilder();
		char lastChar = ' ';
		bool start = true;
		foreach (String s in base.Keys)
		{
			sb.Append((start ? "?" : "&") + s + "=" + HttpContext.Current.Server.UrlEncode(base[s]));
			lastChar = start ? '?' : '&';
			start = false;
		}
		return sb.ToString() + (lastChar == ' ' ? '?' : '&') + append;
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *