Extract (retrieve) numbers from middle of string using C# and VB.Net in ASP.Net

Last Reply 5 months ago By arunkurmi

Posted 5 months ago

hello,

i have this 13 digit number

XXXXX1234567X

i want to extract middle number i.e 1234567 how to do that

like user type in textbo 13 number when user complete the typing  i want to seperate this middle 7 numbers highlight above and show it in label

Posted 5 months ago

Hi nauna,

Check this sample. now take its reference.

HTML

Enter Number :<asp:TextBox ID="txtNumer" runat="server" MaxLength="13" /><br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="OnSubmit" /><br /><br />
<asp:Label ID="lblCard" Text="" runat="server" />

Code

C#

protected void OnSubmit(object sender, EventArgs e)
{
    string Cardnumber = txtNumer.Text.Trim();
    string firstDigits = Cardnumber.Substring(0, 5);
    string middleDigits = Cardnumber.Substring(5, 7);
    string lastDigits = Cardnumber.Substring(Cardnumber.Length - 1, 1);
    string firstMask = new String('X', Cardnumber.Length - middleDigits.Length);
    string lastMask = new String('X', Cardnumber.Length - 12);
    string maskedString = string.Concat(firstMask, middleDigits, lastMask);
    lblCard.Text = maskedString;
}

VB.Net

Protected Sub OnSubmit(ByVal sender As Object, ByVal e As EventArgs)
    Dim Cardnumber As String = txtNumer.Text.Trim()
    Dim firstDigits As String = Cardnumber.Substring(0, 5)
    Dim middleDigits As String = Cardnumber.Substring(5, 7)
    Dim lastDigits As String = Cardnumber.Substring(Cardnumber.Length - 1, 1)
    Dim firstMask As String = New String("X", Cardnumber.Length - middleDigits.Length)
    Dim lastMask As String = New String("X", Cardnumber.Length - 12)
    Dim maskedString As String = String.Concat(firstMask, middleDigits, lastMask)
    lblCard.Text = maskedString
End Sub

Screenshot