Reputation: 151
I have an insert query that inserts the value of a textbox into a database table. It's a credit card number text box, so I only want to store the last 4 digits of the number. How can I do this? I'll show you what I have right now:
cmd.Parameters.Add("@Number", System.Data.SqlDbType.VarChar, 50).Value = txtCardNumber.Text;
I've tried adding " , -4" afterwards, but it doesn't allow that. Any help will be appreciated.
Note: Everything is inserted correctly otherwise.
Upvotes: 2
Views: 740
Reputation: 836
How about this??
cmd.Parameters.Add("@Number", System.Data.SqlDbType.VarChar, 50).Value = txtCardNumber.Text.Substring(txtCardNumber.Text.Length - 4)
or you can also do this although not best solution..
var last4digits = (long.parse(txtCardNumber.Text)%10000).ToString();
cmd.Parameters.Add("@Number", System.Data.SqlDbType.VarChar, 50).Value = last4digits;
Upvotes: 2
Reputation: 499172
This is basic string manipulation.
To get the last four characters of any string:
theString.Substring(theString.Length - 4)
I suggest you take a good look at the different methods and properties defined on the String
class.
Upvotes: 4
Reputation: 98840
Use String.Substring()
method
Retrieves a substring from this instance. The substring starts at a specified character position.
cmd.Parameters.Add("@Number", System.Data.SqlDbType.VarChar, 50).Value = txtCardNumber.Text.Substring(txtCardNumber.Text.Length - 4);
Upvotes: 4