only allow numbers and fullstop (period) in textbox - vb.net

I know that the following code blocks the usser from ussing spaces in a textbox however how do i allow the user to only use numbbers and a fulstop (so i can add values like 1.5)
Private Sub Textbox4_keyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox4.KeyDown
If e.KeyCode = Keys.Space Then
TextBox4.Clear()
MsgBox("Invalid character. No spaces Permited...")
End If

From a usability point of view, testing for valid input in the KeyDown event isn’t good. For example, what happens when the user wants to paste text into your text box?
Furthmore, the user can still paste invalid input using the TextBox’ context menu, your code won’t notice this.
You should allow all input, and then test for validity when the user leaves the text box. VB has an extra event for this, which is fired whenever the text box loses focus: Validating. Use this event (and only this event) to test for valid input.

A simple approach for this might be to look for the "allowed" characters, if not one of them, show the error message.

In last 20years of writing code I always use the following rationale for TextBoxes Check Characters.
First you have to create a separate Class which you may call it (for your convenience) Char_Validation.
Inside to this Class you’ll put a Function which returns Boolean as follows .
Public Class Char_Validation
Public Const Gr As String = "Greek"
Public Const En As String = "English"
Public Const Num As String = "Numbers"
Public Const FullGr As String = "Full Greek"
Public Const FullEn As String = "Full English"
Public Const EnN As String = "English with Numbers"
Public Const GrN As String = "Greek with Numbers"
Public Shared Function ValidateChar(ByVal AsciiChar As String, ByVal CharTable As String, ByVal sender As Object, ByVal e As System.EventArgs) As Boolean
Dim ConvChar As Integer = CUInt(Microsoft.VisualBasic.Asc(AsciiChar))
Dim ConvCharW As Integer = CUInt(Microsoft.VisualBasic.AscW(AsciiChar))
ValidateChar = False
Select Case CharTable
Case En
Select Case ConvChar
Case 65 To 126, 145 To 150, 8, 32 To 47, 58 To 64, 128, 130
ValidateChar = True
End Select
Case EnN
Select Case ConvChar
Case 48 To 57, 65 To 126, 8, 32, 45
ValidateChar = True
End Select
.
.
.
.
.
Case Num
Select Case ConvChar
Case 44 To 57, 92, 8
ValidateChar = True
End Select
End Select
End Function
End Class
At your Class in Form you will use the TextBox_KeyPress on which you’ll use the following code.
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
ErrorProvider1.Clear()
ErrorLabel.ForeColor = Drawing.Color.Black
Select Case Char_Validation.ValidateChar(e.KeyChar, Char_Validation.Num, sender, e)
Case True
Case False
ErrorProvider1.SetError(TextBox1, "Wrong Character Only Numbers")
Beep()
e.KeyChar = ""
End Select
End Sub
Thus you will prohibit the user to place characters out of your decision.
I hope that will cover you from now.

Following code worked for me on : firefox, IE 8, chrome, Safari and iphone.
function dotplaced(myfield){
if(myfield.indexOf(".")===-1){
return false;
}
return true;
}
function NumbersOnly(myfield, e) {
var key;
var keychar;
if (window.event) {
key = window.event.keyCode;
}
else if (e) {
key = e.which;
}
else {
return true;
}
keychar = String.fromCharCode(key);
// control keys
if ((key == null) || (key == 0) || (key == 8) ||
(key == 9) || (key == 13) || (key == 27)) {
return true;
}
// numbers
else if ((("0123456789").indexOf(keychar) > -1)) {
return true;
}
// decimal point jump
else if (!dotplaced(myfield.value) && (keychar == ".")) {
//myfield.form.elements[dec].focus();
return true;
}
else {
return false;
}
}

Related

VB.Net: Retrieve input and display in upper and lower cases

Say I have a textbox that has the following text : "hello" without the quotes. How would I take that text and output something like this : [Hh][Ee][Ll][Ll][Oo]
Is there a better/faster way than manually changing it?
Your question is more in a logic part.
Providing you have a textbox and a button that when you click the button, the output will pop in a message box... just use substring and convert each character to uppercase and lowercase and simply add the brackets like this
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim input As String = TextBox1.Text.Trim
Dim output As String = ""
For index As Integer = 0 To input.Length - 1
output += "[" + input.Substring(index, 1).ToUpper + "" + input.Substring(index, 1).ToLower + "]"
Next
MsgBox(output)
End Sub
End Class
from here below is the code added by Niranjan Kala. The code is not in vb but try to convert it.
//It would be better if you use StringBuilder rather than using SubString Method to create new strings in memory to append in output..See below code snippet:
string message ="hello"; // = TextBox1.Text.Trim()
StringBuilder br = new StringBuilder();
if(!string.IsNullOrEmpty(message))
{
char[] charArray = message.ToArray();
for(int index = 0;index< charArray.Length;index++)
{
br.AppendFormat("[{0}{1}]", Char.ToUpper(charArray[index]), Char.ToLower(charArray[index]));
}
}
string result = br.ToString();
result.Dump();
You can use something like this:
Function ReBuildStr(s As String) As String
Dim result As New System.Text.StringBuilder()
For Each c As Char In s
result.AppendFormat("[{0}{1}]", Char.ToUpper(c), Char.ToLower(c))
Next
Return result.ToString()
End Function
Or if you don't want to use StringBuilder you can use a String using this inside the For:
result &= "[" & Char.ToUpper(c) & Char.ToLower(c) & "]"

Get specific value from .txt file using identifier VB.Net

I try to create a config file using .txt files, here I find it difficult to read the contents of the format.. already from yesterday I searched on google , but no similar case like me or maybe I missed it..
contents of .txt I have is as follows :
Cek Server IP = 192.168.10.1
Server IP = 192.168.10.1
Cek My Website = www.google.com
My Website = www.anothersite.com
this is my code :
WebControl.Source = New Uri("about:blank")
If My.Computer.Network.Ping("XXX") Then
WebControl.Source = New Uri("ZZZ")
Else
MsgBox("CANNOT CONNECT TO SERVER")
Exit Sub
End If
what i want is how to get value "192.168.10.1" From "Cek Server IP" then send to "XXX" and Get Value "192.168.10.1" from "Server IP" then send to "ZZZ"
How can i do that?
Sory for my bad english. Thanks.
As per my understanding, you want to read the values from your .txt file by giving its key. For that, you will have to write a function first that gets a key as a parameter and return the value:
private String GetValue(String key)
{
Boolean isValueFound = false;
String line = null;
//Open your file
using (StreamReader sr = new StreamReader("YourFile.txt"))
{
//Read it line-by-line
while ((line = sr.ReadLine()) != null)
{
//When the required line is found, set the flag and come out of the loop
if (line.Trim().StartsWith(key))
{
isValueFound = true;
break;
}
}
}
if (isValueFound)
{
//Split the line by using = as separator. So at index 0, you have the key and at index 1 you have the value
String[] strArray = line.Split('=');
//Trim the value before returning to get rid of extra spaces
return strArray[1].Trim();
}
else
{
//if value is not found, return null
return null;
}
}
Now you can call the above function like this:
//This line will give you 192.168.10.1
String result = this.GetValue("Cek Server IP");
//This line will return www.google.com
result = this.GetValue("Cek My Website");
For file I/O, the System.IO.File class has some useful methods, and for text files, the ReadLines method is probably what you want. You can then use String.Contains to check for the = character, and String.Split to separate the lines into key and value parts.
You could wrap this up into a class to read and parse your configuration file, and give you access to the specific values, e.g. (you will probably need some Imports and Option Infer On):
Public Class SettingsFile
Private ReadOnly _settings As IDictionary(Of String, String)
Private Sub New(settings As IDictionary(Of String, String))
_settings = settings
End Sub
Public Default ReadOnly Property Item(name As String) As String
Get
Dim value As String = Nothing
_settings.TryGetValue(name, value)
Return value
End Get
End Property
Public Shared Function Load(fileName As String) As SettingsFile
Dim settings = New Dictionary(Of String, String)()
For Each line In File.ReadLines(fileName).Where(Function(x) x.Contains("="))
Dim parts = line.Split("="c)
If parts.Count = 2 Then
settings(parts(0).Trim()) = parts(1).Trim()
End If
Next
Return New SettingsFile(settings)
End Function
End Class
You could then use this class in your code, e.g.:
Dim s = SettingsFile.Load("C:\Path\To\Settings.txt")
Dim s1 = s("Cek Server IP") ' 192.168.10.1
Dim s2 = s("Cek My Website") ' www.google.com
Dim s3 = s("Bad Key") ' Nothing

Unbound DataGridView : Need ComboBox In cell of 2nd column only when user clicks cell

I have a unbound DataGridView with two columns. First column is just string values.
Second column I want to display a combobox, only when user click the cell(not the whole column as DataGridViewColumn). I use the below code which is incorrect and gives me the error : Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore function.
The first column is popuated, and the second column is empty.
The code is as below :
Private Sub DGVFieldsMap_CellEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGVFieldsMap.CellEnter
If e.ColumnIndex = 1 Then
If cboClmCell Is Nothing Then
Dim dgv As DataGridView = CType(sender, DataGridView)
cboClmCell = New DataGridViewComboBoxCell
cboClmCell.Items.Add("A")
cboClmCell.Items.Add("B")
cboClmCell.Items.Add("C")
cboClmCell.Items.Add("D")
cboClmCell.Items.Add("E")
cboClmCell.Items.Add("F")
dgv.Focus()
dgv(e.ColumnIndex, e.RowIndex) = cboClmCell '[Error Here]
isCombo = True
End If
End If
End Sub
Private Sub DGVFieldsMap_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DGVFieldsMap.CellValidating
If e.ColumnIndex = 1 Then
Dim dgv As DataGridView = CType(sender, DataGridView)
If isCombo Then
isCombo = False
cboClmCell = Nothing
dgv(e.ColumnIndex, e.RowIndex) = New DataGridViewTextBoxCell()
End If
End If
End Sub
Can anybody give me a complete working example with two columns, the second column being a ComboBoxCell, but only when user clicks. Also I need to get the selected values in the DataGridView cell. Thanks In Advance.
Don't try to replace the columns in event handlers, instead create a DataGridView with 2 columns, have the 2nd column be your DataGridViewComboBoxColumn. There is a property on that column called "DisplayStyle" which determines how the column looks when not editing. Set it to "Nothing". Now it will look like a textbox until you go into edit mode at which point it looks like a combobox.
I have a similar DataGridView where the first column is a textual label and the second column is ComboBox.
Note: The code below is in C#, but the concept is the same as in vb.net
In the form's load event, call a function that sets up the datasource and creates the columns
private void frmCfgEdit_Load(object sender, EventArgs e)
{
// Fill CFG Data Grid
FillCfgDataGrid();
}
private void FillCfgDataGrid()
{
// Do not automatically generate the columns based on the datasource public fields
dgCFG.AutoGenerateColumns = false;
// Define data source
dgCFG.DataSource = _pDriveElement.CfgTableViewRecs;
// Define data grid columns
SetUpCFGDataGrid(dgCFG);
}
public void SetUpCFGDataGrid(DataGridView dgCFG, String TableIdentifier)
{
// Create datagridview text column
AddGridColumn(dgCFG, "Label", "CfgLabel", 350, typeof(System.String), true, false);
// Create datadridview combobox column
AddGridComboColumn(dgCFG, "Value", 350, typeof(System.String), false, true);
}
public void AddGridColumn(DataGridView dg, String sHeaderText, String sDataPropertyName, int iWidth, Type tyValueType, bool bReadOnly, bool bLastCol)
{
DataGridViewTextBoxColumn colTxt = new DataGridViewTextBoxColumn();
colTxt.HeaderText = sHeaderText;
colTxt.Width = iWidth;
colTxt.ReadOnly = bReadOnly;
// Add the text box to the data grid
dg.Columns.Add(colTxt);
int iColumn = dg.Columns.Count - 1;
// Define bindings to text columns
dg.Columns[iColumn].DataPropertyName = sDataPropertyName;
dg.Columns[iColumn].ValueType = tyValueType;
if (tyValueType == typeof(System.Single)) dg.Columns[iColumn].DefaultCellStyle.Format = "F6";
if (bLastCol) dg.Columns[iColumn].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
if (iColumn > 0) dg.Columns[iColumn].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
public void AddGridComboColumn(DataGridView dg, String sHeaderText, int iWidth, Type tyValueType, bool bReadOnly, bool bLastCol)
{
DataGridViewComboBoxColumn cb = new DataGridViewComboBoxColumn();
cb.FlatStyle = FlatStyle.Flat;
cb.HeaderText = sHeaderText;
cb.Width = iWidth;
cb.ReadOnly = bReadOnly;
dg.Columns.Add(cb);
int iColumn = dg.Columns.Count - 1;
// Combo box is always left aligned
dg.Columns[iColumn].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
if (bLastCol) dg.Columns[iColumn].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}

What is the equivalent of My.Resources in Visual-C++?

I need to iterate through all the resources in a project and basically output their names. I have this done in VB. But I can't figure out what the equivalent of My.Resources.ResourceManager is in VC++.
Here's the VB code.
Dim objResourceManager As Resources.ResourceManager = My.Resources.ResourceManager
Dim objResourceSet As Resources.ResourceSet = objResourceManager.GetResourceSet(CultureInfo.CurrentCulture, True, True)
Dim iterator As IDictionaryEnumerator = objResourceSet.GetEnumerator()
Private Sub go()
Dim s As String = iterator.Key
Debug.WriteLine(s)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If iterator.MoveNext Then
go()
Else
iterator.Reset()
If iterator.MoveNext Then
go()
Else
Throw New Exception("No elements to display")
End If
End If
End Sub
And this is how far I am in VC++.
private:
Resources::ResourceManager^ rmgnr;
Resources::ResourceSet^ rSet;
public:
Form1(void)
{
rmgnr = gcnew System::Resources::ResourceManager(L"Resources ProjectCPP",Reflection::Assembly::GetExecutingAssembly());
//This is the problem as I can't find the equivalent in c++
rSet = rmgnr->GetResourceSet(CultureInfo::CurrentCulture,true,true);
Please help me figure this out.
I think you just want:
rmgnr = gcnew System::Resources::ResourceManager(GetType());
You can use something like the following for unmanaged C++:
HRSRC hResInfo = FindResource(hInstance, MAKEINTRESOURCE(resourceId), type);
HGLOBAL hRes = LoadResource(hInstance, hResInfo);
LPVOID memRes = LockResource(hRes);
DWORD sizeRes = SizeofResource(hInstance, hResInfo);
You will need to change the type and resourceId to match your resource. Not sure if its an image or icon or what kind of resource, but you would use something like:
FindResource(hInstance, MAKEINTRESOURCE(bitmapId), _T("PNG"));
For Managed C++, try something like the following:
Bitmap *MyBitmap;
String *Msg;
Reflection::Assembly *MyAssembly;
IO::Stream *ResourceStream;
MyAssembly = System::Reflection::Assembly::GetExecutingAssembly();
ResourceStream = MyAssembly->GetManifestResourceStream(ImageName);
if (ResourceStream != NULL)
{
MyBitmap = new Bitmap(ResourceStream);
Msg = String::Format("GetIcon: {0}, OK", ImageName);
}
else
Msg = String::Format("GetIcon: {0}, Failed", ImageName);
// MyBitmap countains your resource
You will need to replace ImageName with the name of your resource you are trying to grab. Again, I'm assuming its an image resource you are trying to grab.

Display `00` instead of `0` in a NumericUpDown control

I'm letting users select a date/time for a scheduled task to run, using two NumericUpDowncontrols.
I'd like one-digit values to be padded with a leading 0, so as to display 09:00 instead of 9:0.
The definitive solution is to use a DateTimePickerwith ShowUpDown set to True and Format set to Time or Custom. In the latter case, you'd use hh:mm or HH:mm as a custom format.
class CustomNumericUpDown:System.Windows.Forms.NumericUpDown
{
protected override void OnTextBoxTextChanged(object source, EventArgs e)
{
TextBox tb = source as TextBox;
int val = 0;
if (int.TryParse(tb.Text,out val))
{
if (val < 10)
{
tb.Text = "0" + val.ToString();
}
}
else
{
base.OnTextBoxTextChanged(source, e);
}
}
}
I had to do this this morning and came up with a Customised Numeric Up Down for my Windows Forms application. You should be able to change this easily enough to VB.NET.
This is not possible with a NumericUpDown Control.
I have a clever idea~
Why don't you put a textbox covering the textbox part of the numericupdown control (only the scroll of numericupdown will be shown)?
Set your textbox with "00" as the initial value, then disable it, so that the user can't control your textbox.
Then type these codes:
Private Sub numericupdown1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ndFrom.ValueChanged
If numericupdown1.Value < 10 Then
textbox1.Text = "0" & numericupdown1.Value
Else
textbox1.Text = numericupdown1.Value
End If
End Sub
class MyNumericUpDown : System.Windows.Forms.NumericUpDown
{
public override string Text
{
get
{
return base.Text;
}
set
{
if (value.Length < 2)
value = "0" + value;
base.Text = value;
}
}
}