我通過表單中的文本框接受用戶的字符串值。然後將它用於對數據庫表的查詢,雖然它是一個字符串,但我只需要輸入的唯一字符是整數。用戶輸入 - 數據驗證
我試過了各種方法,例如INT32
和TryParse
函數。但是,當嘗試執行IF ELSE
或TRY CATCH
時,我遇到了一些問題,以防止在輸入「可接受」之前執行任何操作。
什麼是最簡單的方法,只允許整個數字輸入到文本框中,或識別除整數之外的任何內容,並且執行失敗?
我通過表單中的文本框接受用戶的字符串值。然後將它用於對數據庫表的查詢,雖然它是一個字符串,但我只需要輸入的唯一字符是整數。用戶輸入 - 數據驗證
我試過了各種方法,例如INT32
和TryParse
函數。但是,當嘗試執行IF ELSE
或TRY CATCH
時,我遇到了一些問題,以防止在輸入「可接受」之前執行任何操作。
什麼是最簡單的方法,只允許整個數字輸入到文本框中,或識別除整數之外的任何內容,並且執行失敗?
是的,你可以使用int.TryParse
:
string selectSql = "SELECT * FROM SomeTable WHERE ID = @ID";
int id;
if (!int.TryParse(txtID.Text, out id))
MessageBox.Show("ID must be an integer.");
else
{
using (var myCon = new SqlConnection(connectionString))
using (var selectCommand = new SqlCommand(selectSql, myCon))
{
selectCommand.Parameters.AddWithValue("@ID", id);
myCon.Open();
using (var reader = selectCommand.ExecuteReader())
{
// do something with the records
}
}
}
你也可以使用一個NumericUpDown
control。
使用NumericUpDown控件,而不是一個TextBox
您可以編寫自己的類,從文本框繼承:
public class NumericTextBox : TextBox
{
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
var key = e.KeyChar + "";
if (key == "\b")
return;
double number;
string newText = Text.Remove(SelectionStart, SelectionLength).Insert(SelectionStart, key);
if (newText.Length == 1 && key == "-")
return;
if (!double.TryParse(newText, NumberStyles.Float, CultureInfo.InvariantCulture, out number))
{
e.Handled = true;
}
}
public double Value
{
get { return Text.Length == 0 ? 0 : double.Parse(Text, CultureInfo.InvariantCulture); }
}
}
正如另一種選擇,你可以使用TextChanged事件文本框。
int.TryParse文本每次更改值,如果它不工作,只需清除文本框(或保留最後一個值的工作和恢復到失敗)。
我知道的3點可能的方式來做到這一點:
在文本框的TextChanged事件刪除無效字符:
private void txb_TextChanged(object sender, EventArgs e)
{
int selStart = txb.SelectionStart;
string result = txb.Text;
// remove all that aren't digits
result = Regex.Replace(result, @"[^0-9]", string.Empty);
txb.Text = result;
// move cursor
if (selStart > txb.Text.Length)
txb.Select(txb.Text.Length, 0);
else txb.Select(selStart, 0);
}
擴展TextBox控件,而忽略所有無效的按鍵是用戶按下
public class IntegerTextBox : TextBox
{
private Keys[] int_allowed = {
Keys.D1,
Keys.D2,
Keys.D3,
Keys.D4,
Keys.D5,
Keys.D6,
Keys.D7,
Keys.D8,
Keys.D9,
Keys.D0,
Keys.NumPad0,
Keys.NumPad1,
Keys.NumPad2,
Keys.NumPad3,
Keys.NumPad4,
Keys.NumPad5,
Keys.NumPad6,
Keys.NumPad7,
Keys.NumPad8,
Keys.NumPad9,
Keys.Back,
Keys.Delete,
Keys.Tab,
Keys.Enter,
Keys.Up,
Keys.Down,
Keys.Left,
Keys.Right
};
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Modifiers == Keys.Control) return;
if (!int_allowed.Contains(e.KeyCode))
{
e.SuppressKeyPress = true;
}
}
}
}
process KeyDown and/or KeyPress event並在不允許的情況下取消它
NumericUpDown允許其他字符,如.- – William