Add your own error message to a ValidationSummary

There are time where you need to display a message to the users.  Here’s how to do it with a Validation Summary on your ASP.NET page.
I use this when I want to display an error message that doesn’t come from an exception or another validation.
This is helpful when you want all messages to have the same look and feel.
You MUST have a validation summary on your page otherwise nothing happens.

Below is the code.

CustomValidator val = new CustomValidator();
val.IsValid = false;
val.ErrorMessage = "My error message for the ValidationSummary";
this.Page.Validators.Add(val);

You create create a custom validator, set it to invalid, define the error message, and add it to your page.

[tweetmeme only_single=”false”]
Advertisements

How to get a reference to the control that caused a post back

Here is some old code I found (in VB.NET) the will tell you what control caused the post back.

  ' Return a reference to the control that caused the last postback,
'  even from the Page_Load event!
' It requires in input a reference to the posted-back page
' (this is necessary if you want to be able to move this function in a separate 
' class
' instead of in a page's codebehind class
'
' Example:
'    Private Sub Page_Load(ByVal sender As System.Object,
'  ByVal e As System.EventArgs) Handles MyBase.Load
'        Dim postbackCtl As Control = GetPostbackControl(Me)
'        If Not postbackCtl Is Nothing Then
'            lblResult.Text = postbackCtl.ID
'        End If
'    End Sub

Function GetPostbackControl(ByVal targPage As Page) As Control
    If targPage.IsPostBack Then
        ' try to find the name of the postback control in the hidden 
        ' __EVENTTARGET field
        Dim ctlName As String = targPage.Request.Form("__EVENTTARGET")
        ' if the string is not null, return the control with that name
        If ctlName.Trim().Length > 0 Then
            Return targPage.FindControl(ctlName)
        End If
        ' the trick above does not work if the postback is caused by standard 
        ' buttons.
        ' In that case we retrieve the control the ASP-way: by looking in the 
        ' Page's Form collection
        ' to find the name of a button control, that actually is the control 
        ' that submitted the page
        Dim keyName As String
        For Each keyName In targPage.Request.Form
            Dim ctl As Control = targPage.FindControl(keyName)
            ' if a control named as this key exists,
            '  check whether it is a button - if it is, return it!
            If Not ctl Is Nothing Then
                If TypeOf ctl Is Button Then
                    Return ctl
                End If
            End If
        Next
    End If

    Return Nothing
End Function
[tweetmeme only_single=”false”]

Method to strip out special characters from a string.

Special characters can cause all kind of trouble.
So here is a method that you pass in a string and all the special characters will be removed.

 

public static string StripSpecialCharacters(string stringToConvert)
        {
            stringToConvert = stringToConvert.Replace("~", string.Empty);
            stringToConvert = stringToConvert.Replace("#", string.Empty);
            stringToConvert = stringToConvert.Replace("%", string.Empty);
            stringToConvert = stringToConvert.Replace("&", string.Empty);
            stringToConvert = stringToConvert.Replace("*", string.Empty);
            stringToConvert = stringToConvert.Replace("{", string.Empty);
            stringToConvert = stringToConvert.Replace("}", string.Empty);
            stringToConvert = stringToConvert.Replace("\\", string.Empty);
            stringToConvert = stringToConvert.Replace(":", string.Empty);
            stringToConvert = stringToConvert.Replace("<", string.Empty);
            stringToConvert = stringToConvert.Replace(">", string.Empty);
            stringToConvert = stringToConvert.Replace("?", string.Empty);
            stringToConvert = stringToConvert.Replace("/", string.Empty);
            stringToConvert = stringToConvert.Replace("|", string.Empty);
            stringToConvert = stringToConvert.Replace("\"", string.Empty);
            return stringToConvert;
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

Detect who the current user in a SharePoint web part

It’s easy to detect who the current authenticated in ASP.HET (HttpContext.Current.User), but that doesn’t work in a web part.
So in a web part, you need to open a web and then you access the current user.

Below is an example (you just have to specify the “SiteToOpen”).

 

using (SPWeb webSite = SPContext.Current.Site.OpenWeb(SiteToOpen))
{
     //Determine who the current user is
        String currentUser = webSite.CurrentUser.Name;
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

Programmatically set url field on list

I had to find a way to programmatically add items to list that has a url field.
Here is an example of how to do it.
When you set the field that is an URL you have specify a url a coma (and a space) and the value to display.

 

using (SPWeb webSite = SPContext.Current.Site.OpenWeb(SiteToOpen))
{
       SPListCollection lists = webSite.Lists;
       SPList theLlist = webSite.Lists["listName"];
       string documentUrl = String.Empty;
       foreach (DocumentItems d in documents)
       {
            SPListItem listItem = theLlist.Items.Add();
             listItem["Title"] = "ItemTitle";
             listItem["Link"] = "URL" + ", " + "Display Value";
 
             listItem.Update();
        }
 }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }


.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

How to add a required field validator to a SharePoint web part.

You just have to set the ID property of the control, then set the control to validate to the ID of the control.

Below is an example

//Declare Controls
private TextBox _txtFirstName = new TextBox();
RequiredFieldValidator _rfvFirstName = new RequiredFieldValidator();

//Add text box
this._txtFirstName.ID = “txtFirstName”;
this.Controls.Add(_txtFirstName);

//Required field validator
_rfvFirstName.Text = “* First Name is required!”;
_rfvFirstName.Display = ValidatorDisplay.Dynamic;
_rfvFirstName.ControlToValidate = _txtFirstName.ID;
_rfvFirstName.ForeColor = Color.Red;
_rfvFirstName.ValidationGroup = “adduser”;
this.Controls.Add(_rfvFirstName);

[tweetmeme only_single=”false”]

How to add a row click event to a gridview

So I ran across the problem of I need a web page to do something if a user clicked a row in a grid.
It wasn’t going to work for the user to click a button, the whole row had to be clickable.

Adding a row data bound event solved the problem.
I also change the background color on mouse over (and mouse out).

When the user clicks the row they get redirected to a page (with a query string parm so I know what row they clicked on).

 

   1: protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)

   2: {

   3:     if (e.Row.RowType == DataControlRowType.DataRow)

   4:     {

   5:         e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#ceedfc'");

   6:         e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=''");

   7:         e.Row.Attributes.Add("style", "cursor:pointer;");

   8:         e.Row.Attributes.Add("onclick", "location='detail.aspx?id=" + e.Row.Cells[0].Text + "'");

   9:     }

  10: }

Clear Controls on screen

Here is a method that will clear all the controls on your screen (as long as it matches one of the controls in the method).  It recursively calls itself until all the controls are clear.

Here is an example of how you call it:
ClearControlsOnScreen(this.Page);

  public void ClearControlsOnScreen(Control parent)
        {
            try
            {
                foreach (Control _ChildControl in parent.Controls)
                {
                    if ((_ChildControl.Controls.Count > 0))
                    {
                        ClearControlsOnScreen(_ChildControl);
                    }
                    else
                    {

                        TextBox textbox = _ChildControl as TextBox;
                        if (textbox != null)
                        {
                            textbox.Text = string.Empty;
                        }

                        DropDownList dropdownlist = _ChildControl as DropDownList;
                        if (dropdownlist != null)
                        {
                            dropdownlist.ClearSelection();
                        }

                        CheckBox checkBox = _ChildControl as CheckBox;
                        if (checkBox != null)
                        {
                            checkBox.Checked = false;
                        }

                        CheckBoxList checkBoxList = _ChildControl as CheckBoxList;
                        if (checkBoxList != null)
                        {
                            checkBoxList.ClearSelection();
                        }

                        GridView gridView = _ChildControl as GridView;
                        if (gridView != null)
                        {
                            gridView.DataSource = null;
                            gridView.DataBind();
                        }

                    }
                }

            }
            catch (Exception ex)
            {
                throw ;
            }
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Run app as a specific user

Running an application as a specific user is common practice, but sometimes it’s helps to debug your application if you can run it as a specific user.

This does not change security context which the application runs as.
This works if you have your own user/role tables that control application security.

So if you add a key to your config file (web.config for example) then anytime you need to get the current user just call this method.

If the strUsername key is set to “Default” it will run as the current user.
If you set it to some other username it will return that username.

public static string GetUsername()
        {
            try
            {
                if (System.Configuration.ConfigurationManager.AppSettings["strUsername"].ToString() == "Default")
                {
                    return HttpContext.Current.User.Identity.Name.Substring(HttpContext.Current.User.Identity.Name.IndexOf('\\') + 1).ToLower();
                }
                else
                {
                    return System.Configuration.ConfigurationManager.AppSettings["strUsername"].ToString();
                }
             }
            catch (Exception ex)
            {
                throw ;
            }
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Helper method to capitalize a string

Here is a method that you a pass a string an it returns it correctly capitalized.
It makes uses of the System.Globalization namespace.
I have found that it is easier to wrap this call in your own method (like in a helper class) instead of typing it all our or remembering to include the Globalization namespace.

public static string Capitalize(string value)
        {
            try
            {
                return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(value);
            }
            catch (Exception ex)
            {
                throw ;
            }
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }