Как сделать кнопку отключенной, когда в текстовом поле нет текста? - PullRequest
1 голос
/ 24 октября 2019

Мне нужно, чтобы кнопки BtnCalculate и BtnMessageBox были отключены, когда в текстовых полях TxtQuantity и TxtPrice ничего нет, в том числе и при запуске программы. Кто-нибудь знает как это сделать? Очевидно, что сообщение «Количество и цена не должны быть пустыми» больше не потребуется в коде после внесения изменений. Заранее большое спасибо! Может быть просто, но ИДК, что я делаю.

Вот код:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void BtnCalculate_Click(object sender, EventArgs e)
    {
        //declare Variables
        int intQuantity;
        Decimal decPrice;
        Decimal decTotal;
        //make sure quantity and price are the same
        // if string is null or empty retuern textbox

        Decimal TAX_RATE = 0.06m;
        if (OosTax.Checked == true)
            { TAX_RATE = 0.09m; }
        if ((TxtQuantity.Text.Trim().Length == 0 || (TxtPrice.Text == "")))
        { MessageBox.Show("Quantity and price must not be empty", "Calculator", MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2); }
        else
        {
            try
            {
                intQuantity = Int32.Parse(TxtQuantity.Text);
                decPrice = Decimal.Parse(TxtPrice.Text);
                decTotal = (intQuantity * decPrice) * (1 + TAX_RATE);
                LblMessage.Text = decTotal.ToString("C");
            }
            catch (Exception ex)
            { // Send Focus to Quantity
                TxtQuantity.Focus();
                TxtQuantity.SelectAll();
            }
        }
    }

    private void BtnMessageBox_Click(object sender, EventArgs e)
    {
        //declare Variables
        int intQuantity;
        Decimal decPrice;
        Decimal decTotal;
        string message = "Your Total Is: ";
        Decimal TAX_RATE = 0.06m;
        if (OosTax.Checked == true)
        { TAX_RATE = 0.09m; }
        //make sure quantity and price are the same
        // if string is null or empty retuern textbox

        if ((TxtQuantity.Text.Trim().Length == 0 || (TxtPrice.Text == "")))
        { MessageBox.Show("Quantity and price must not be empty", "Calculator", MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2); }
        else
        {
            try
            {
                intQuantity = Int32.Parse(TxtQuantity.Text);
                decPrice = Decimal.Parse(TxtPrice.Text);
                decTotal = (intQuantity * decPrice) * (1 + TAX_RATE);
                // Display Total Currency as
                MessageBox.Show(message + System.Environment.NewLine + decTotal.ToString("C"), "Chapter Two",
                    MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);

            }
            catch (Exception ex)
            { // Send Focus to Quantity
                TxtQuantity.Focus();
                TxtQuantity.SelectAll();
            }

        }
    }

    private void BtnExit_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void BtnClear_Click(object sender, EventArgs e)
    {
        LblMessage.Text = String.Empty;
    }
}

Ответы [ 2 ]

1 голос
/ 24 октября 2019

используйте событие TextChanged для текстового поля

, например

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        button1.Enabled = (textBox1.Text.Length > 0);
    }

, если вы хотите сделать это в загруженном окне,

используйте

textBox1_TextChanged(null,null);

при загруженном событии

0 голосов
/ 24 октября 2019

Я бы просто написал метод, который устанавливает свойство кнопки «Включено» на основе длины текста текстового поля двух элементов управления текстовым полем, а затем вызвал бы его из события Load формы и события TextChanged текстовых полей:

private void Form1_Load(object sender, EventArgs e)
{
    ButtonEnabler();
}

private void txtPrice_TextChanged(object sender, EventArgs e)
{
    ButtonEnabler();
}

private void txtQuantity_TextChanged(object sender, EventArgs e)
{
    ButtonEnabler();
}

private void ButtonEnabler()
{
    bool enabled = txtPrice.TextLength > 0 && txtQuantity.TextLength > 0;
    btnCalculate.Enabled = enabled;
    btnMessageBox.Enabled = enabled;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...