Durga
Durga

Reputation: 1303

How can I write code For multiple textbox leave event only once

I am using this code on textbox Leave event to Make first Letter of textbox to uppercase,On form I have Particular textboxes for which I want to get same Functionality done ,but Is there any way so that I don't need to write same code in each textbox leave event ,How can I do this

private void txtAdrs2A_Leave(object sender, EventArgs e)
{
    if (txtAdrs2A.Text.Length >= 1)
        txtAdrs2A.Text = txtAdrs2A.Text.Substring(0, 1).ToUpper() + txtAdrs2A.Text.Substring(1);
}

Upvotes: 0

Views: 1584

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

Use sender parameter instead of specifying the TextBox by its Id:

private void TextBox_Leave(object sender, EventArgs e)
{
    var box = sender as TextBox;

    if(box != null && box.Text.Length > 0)
        box.Text = box.Text.Substring(0, 1).ToUpper() + box.Text.Substring(1);
}

Upvotes: 1

user2509901
user2509901

Reputation:

Use sender

    private void text_Leave(object sender, EventArgs e)
    {
        TextBox text = (TextBox)sender;
        if (text.Text.Length >= 1)
        {
            text.Text = text.Text.Substring(0, 1).ToUpper() + text.Text.Substring(1
        }
    }

Then loop through all textboxes to assign the event to them

    foreach (TextBox t in this.Controls.OfType<TextBox>())
    {
        t.Leave += new EventHandler(text_Leave);
    }

Upvotes: 1

Related Questions