簡體   English   中英

只允許在 winform 組合框中使用整數

[英]Only allow integers in a winform combobox

我目前正在使用 c# 對照片編輯器進行編程,我目前正在設計允許鋼筆工具更改大小的功能。 除了一個問題外,它可以完美運行。 這是一些背景信息: 所以在我的組合框中,有 10 個項目,每個項目都是數字 1 - 10。如果我選​​擇一個,或者直接在組合框中輸入一些數字,它會將筆的大小設置為那個。 問題是,如果我輸入一個字母,它會給我一個

索引超出范圍異常

.

有沒有辦法讓組合框只接受整數和浮點數? 基本上我的意思是,如果我按下3 ,筆的大小將更改為 3。但是如果我按下H ,它什么也不做。

您可以選擇兩個選項之一。 第一個選項是通過禁用鍵入來限制用戶鍵入comboobx。 這可以通過在page_load中提供此代碼來實現

 comboBox1.DropDownStyle to ComboBoxStyle.DropDownList

或訪問如下所示的值:

       if (int.TryParse(comboBox1.Text, out BreshSize))
        {
            // Proceed
        }
        else 
        { 
        //Show errror message
        }  

該實現應允許您查看新值是否為整數並采取相應措施。 當您開始檢查該值時,可以將其放置在代碼中。 “ 2”將替換為您要檢查的字符串。

    int currInt = 0;
    int tryInt = 0;
    if(int.TryParse("2", out tryInt))
    {
        currInt = tryInt;         
    }
    else
    {
        //reset or display a warning
    }

另外,您可以使用KeyPress處理程序來確保只鍵入了數字。

private void txtPenToolSize_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }
}

一種適用於具有不同系統十進制分隔符(語言環境)和 texbox/combobox 的國際用戶的通用實現,不僅允許Int數字格式(雙精度、浮點數、十進制等)。

    private void comboTick_KeyPress(object sender, KeyPressEventArgs e)
    {
        //this allows only numbers and decimal separators
        if (!char.IsControl(e.KeyChar) 
            && !char.IsDigit(e.KeyChar) 
            && (e.KeyChar != '.') 
            && (e.KeyChar != ',') )
        {
            e.Handled = true; //ignore the KeyPress
        }
        
        //this converts either 'dot' or 'comma' into the system decimal separator
        if (e.KeyChar.Equals('.') || e.KeyChar.Equals(','))
        {
            e.KeyChar = ((System.Globalization.CultureInfo)System.Globalization.CultureInfo.CurrentCulture)
                .NumberFormat.NumberDecimalSeparator
                .ToCharArray()[0];
            e.Handled = false; //accept the KeyPress
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM