简体   繁体   English

使用C#中的TextBox验证事件

[英]Validating event with TextBox in C#

So, I have 2 forms. 因此,我有2种形式。 The main on has a TextBox and if I press F1 it will open a new form with a DataGridView depending on the inserted values on the TextBox . 最主要的是一个TextBox ,如果我按F1 ,它将根据TextBox上插入的值使用DataGridView打开一个新窗体。 After double clicking in that row from the second form it will go again for the main form and fill the TextBox with the selected row. 在第二个表单中双击该行后,它将再次进入主表单,并用选定的行填充TextBox

Then, in the main form, I have a Validating event on the TextBox and it will be able to depending on that value show it in the Main form DataGridView . 然后,在主窗体中,我在TextBox上有一个Validating事件,它可以根据该值在Main Form DataGridView显示它。

Unfortunately it doesn't work and I think the issue comes from the CauseValidation from other components. 不幸的是,它不起作用,我认为问题出自其他组件的CauseValidation I disabled it by using for example: dataGridView1.CauseValidation = false; 我使用例如禁用它: dataGridView1.CauseValidation = false; , but still the same. ,但仍然相同。

This is the code on the TextBox event: 这是TextBox事件上的代码:

    private void txtCargs_Validating(object sender, CancelEventArgs e)
    {
        e.Cancel = false;
        try
        {
            SqlConnection con = new SqlConnection(cs.DBConnP);
            con.Open();

            string querySelect = @"SELECT RTRIM(CL.Cargs) AS 'Cargs', RTRIM(S.Abvs) AS 'Abss',  RTRIM(CL.Linha) AS 'Linha', RTRIM(CL.Qtd) AS 'Quantity'
                                    FROM CargaCab CC (NOLOCK)
                                    INNER JOIN CargsLin CL (NOLOCK) ON CC.Cargs = CL.Cargs
                                    INNER JOIN Stock S (NOLOCK) ON CL.Code = S.Code 
                                    INNER JOIN Marks M (NOLOCK) ON S.Marks = M.Marks
                                    WHERE CC.Date >= GETDATE() - 120 AND CL.State NOT IN ('F', 'A') AND S.TypeEmb = 'P' 
                                    AND CC.TypeD = 'OCS' AND CL.Cargs = '" + txtCargs.Text.Trim() + "' ORDER BY CL.Carga, S.Marks DESC, S.Abvs";
            cmd = new SqlCommand(querySelect);
            cmd.Connection = con;

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            DataSet ds = new DataSet();
            da.Fill(ds, "CargaCab");

            dataGridView1.DataSource = ds.Tables["CargaCabee"].DefaultView;

            dataGridView1.Columns[0].ReadOnly = true;
            dataGridView1.Columns[1].ReadOnly = true;
            dataGridView1.Columns[2].ReadOnly = true;
            dataGridView1.Columns[3].ReadOnly = false;

            con.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error\nDetalhes: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

What should I do? 我该怎么办?

Short Term 短期

Instead of putting all the logic in the txtCargs_Validating event, make a method that the 2nd form calls when its closed. 而不是将所有逻辑放在txtCargs_Validating事件中,而是创建一种在第二个窗体关闭时调用的方法。 You can do this by passing the instance of the 1st form to the 2nd, eg, 您可以通过将第一个表单的实例传递给第二个表单来执行此操作,例如,

public class SecondForm : Form {

  private Form _1stForm;
  public SecondForm(Form 1stForm)
  {
    _1stForm = 1stForm;
  }

... ...

public SecondForm_Closing(object sender, EventArgs e)
{
_1stForm.SetTheTextBox(theRowValueSelected);
}

Calling Code from the main form: 从主要形式调用代码:

var frm = new SecondForm(this);
frm.Show();

Long Term 长期

The better solution is to have all your Code in a Business logic layer (like a Controller in MVC, or a ModelView in MVVM) and BIND all the UI Controls to the data structures in the business logic layer. 更好的解决方案是将所有代码都放在业务逻辑层中(例如MVC中的Controller或MVVM中的ModelView),并将所有UI控件绑定到业务逻辑层中的数据结构。

Either way save the validating event for validating, eg: 两种方式都保存用于验证的验证事件,例如:

 MessageBox.Show("Error\nDetalhes: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

I suggest, make this event your customized function instead with bool return type. 我建议将此事件设置为您的自定义函数,而不要使用bool返回类型。 use a text_changed event on the text box, and Then call Validate function. 在文本框中使用text_changed事件,然后调用Validate函数。 I've tried sample Textbox_Validating event and its called at form closing. 我尝试了示例Textbox_Validating事件及其在表单关闭时的调用。

 private void txtCargs_TextChanged(object sender, EventArgs e)
        {
            if (ValidateText())
            {
                //Then do this
            }
        }

        private bool ValidateText()
        {
            bool Isvalidated = false;

            try
            {
                SqlConnection con = new SqlConnection(cs.DBConnP);
                con.Open();

                string querySelect = @"SELECT RTRIM(CL.Cargs) AS 'Cargs', RTRIM(S.Abvs) AS 'Abss',  RTRIM(CL.Linha) AS 'Linha', RTRIM(CL.Qtd) AS 'Quantity'
                                    FROM CargaCab CC (NOLOCK)
                                    INNER JOIN CargsLin CL (NOLOCK) ON CC.Cargs = CL.Cargs
                                    INNER JOIN Stock S (NOLOCK) ON CL.Code = S.Code 
                                    INNER JOIN Marks M (NOLOCK) ON S.Marks = M.Marks
                                    WHERE CC.Date >= GETDATE() - 120 AND CL.State NOT IN ('F', 'A') AND S.TypeEmb = 'P' 
                                    AND CC.TypeD = 'OCS' AND CL.Cargs = '" + txtCargs.Text.Trim() + "' ORDER BY CL.Carga, S.Marks DESC, S.Abvs";
                cmd = new SqlCommand(querySelect);
                cmd.Connection = con;

                SqlDataAdapter da = new SqlDataAdapter(cmd);

                DataSet ds = new DataSet();
                da.Fill(ds, "CargaCab");

                dataGridView1.DataSource = ds.Tables["CargaCabee"].DefaultView;

                dataGridView1.Columns[0].ReadOnly = true;
                dataGridView1.Columns[1].ReadOnly = true;
                dataGridView1.Columns[2].ReadOnly = true;
                dataGridView1.Columns[3].ReadOnly = false;

                con.Close();
                Isvalidated = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error\nDetalhes: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Isvalidated = false;
            }

            return Isvalidated;
        }

I think the problem here is that you want a fix to your solution, rather than solve your problem. 我认为这里的问题是您想要解决方案,而不是解决问题。

Here's a quick sketch of how I think this can be achieved: 这是我认为如何实现的简要概述:

public class Form1 : Form
{
    public TextBox textBox1 { get; set; }

    public Button button1 { get; set; }

    private void button1_Click(object sender, EventArgs e)
    {
        var form = new Form2();
        form.Show();
        textBox1.Text = form.val;
        //do your sql stuff here
    }
}

public class Form2 : Form
{
    public DataGridView datagriview1 { get; set; }

    public string val { get; set; }

    private void datagriview1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex > -1)
            val = datagriview1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
        Close();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM