About Me

My photo
Fort Worth, TX, United States
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, July 6, 2007

Replace First Occurrence of a String in C#

I had a need to replace only the first occurrence of a substring within a string, and C# doesn't seem to have a way of doing this with the out-of-the-box String methods. So, I rolled my own:

public static string ReplaceFirstOccurrence(string original, string oldValue, string newValue)
{
    if (String.IsNullOrEmpty(original))
        return String.Empty;
    if (String.IsNullOrEmpty(oldValue))
        return original;
    if (String.IsNullOrEmpty(newValue))
        newValue = String.Empty;
    int loc = original.IndexOf(oldValue);
    return original.Remove(loc, oldValue.Length).Insert(loc, newValue);
}

If you're interested, here is the test case for this method:
[TestClass]
    public class ReplaceFirstOccurrenceTest
    {
        [TestMethod]
        public void TestReplaceFirstOccurrence()
        {
            Assert.AreEqual("", StringUtil.ReplaceFirstOccurrence(null, null, null));
            Assert.AreEqual("", StringUtil.ReplaceFirstOccurrence("", "", ""));
            Assert.AreEqual("Th is what is right.",
                StringUtil.ReplaceFirstOccurrence("This is what is right.", "is", null));
            Assert.AreEqual("Th is what is right.",
                StringUtil.ReplaceFirstOccurrence("This is what is right.", "is", ""));
            Assert.AreEqual("This is what is right.",
                StringUtil.ReplaceFirstOccurrence("This is what is right.", null, ""));
            Assert.AreEqual("This is what is right.",
                StringUtil.ReplaceFirstOccurrence("This is what is right.", "", "stuff"));
        }
    }

Sunday, June 24, 2007

Get LoadPostData to fire on Web Custom Control with ASP.NET 2.0 (C#)

I was trying to write my first web custom composite control and for the life of me, I couldn't get the LoadPostData event to fire. After wrestling with this for a day, I stumbled onto this site that laid it down step-by-step. After checking these things, it worked.

Here's the article for reference:

LoadPostData doesn't fire

I've struggled with this a couple of times, but I think I've got it figured out now. When I implement IPostBackDataHandler on my ASP.NET server control, my LoadPostData event doesn't get hit. This is because I haven't read the MSDN documentation properly.

For a ASP.NET server control to handle postback data correctly, it has to meet the following criteria.
1. The class must implement IPostBackDataHandler.
2. Implement LoadPostData to load the form data.
3. The name (not the ID!) of one of the html controls it renders must exactly match the UniqueID of the control (I always forget this one).
4. Implement RaisePostDataChangedEvent.

Not too tricky.

Blog Archive