【问题标题】:c# TextBox not clearingc#文本框不清除
【发布时间】:2013-11-22 16:15:37
【问题描述】:

我有一个写入 Access 数据表的程序,然后信息显示在数据网格中。当文本框中出现 6 位数字后跟 "L" 时触发此事件。 我在代码中有"TextBox1.Clear();",它清除了6个数字,但没有"L"

这是我的代码:

  private void Registration_Main(object sender, KeyPressEventArgs e)
    {
        SqlConnection DBConnection = new SqlConnection("Data Source=DATABASE;Initial Catalog=imis;Integrated Security=True");
        SqlCommand cmd = new SqlCommand();
        Object returnValue;
        Object returnName;
        string txtend = textBox1.Text;


        if (e.KeyChar == 'L')
        {
            DBConnection.Open();
        }


        if (DBConnection.State == ConnectionState.Open)
        {
            if (textBox1.Text.Length != 6) return;
            {
                cmd.CommandText = ("SELECT last_name +', '+ first_name from name where id =@Name");
                cmd.Parameters.Add(new SqlParameter("Name", textBox1.Text.Replace(@"L", "")));
                cmd.CommandType = CommandType.Text;
                cmd.Connection = DBConnection;
                returnValue = cmd.ExecuteScalar() + "\t " + textBox1.Text.Replace(@"L", "");
                returnName = cmd.ExecuteScalar();

                DBConnection.Close();

                AccessDB_Connection(returnName);
            }

            textBox1.Clear();
        }
    }

    private void AccessDB_Connection(object returnName)
    {
        String varID;
        Object varName;

        varID = textBox1.Text.Replace(@"L", "").ToString();
        varName = returnName;

        OleDbConnection OLEDB_Connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\Test Applications\\Tablet Registration - Access Database\\Tablet Registration - Access\\Tablet Registration - Access\\Registration.accdb"); 
        OleDbCommand updateCmd = new OleDbCommand();

        try
        {
            updateCmd.CommandText = "INSERT INTO TestDB ([Name], [ID]) VALUES (@NAME, @ID)";
            updateCmd.Parameters.AddWithValue("@NAME", varName);
            updateCmd.Parameters.AddWithValue("@ID", varID);
            OLEDB_Connection.Open();
            updateCmd.Connection = OLEDB_Connection;
            updateCmd.ExecuteNonQuery();
            this.testDBTableAdapter.Fill(this.registrationDataSet1.TestDB);
            OLEDB_Connection.Close();
        }
        catch 
        {
        }
    }

非常感谢任何帮助!

【问题讨论】:

  • @Bhavesh 我认为这不会有什么不同
  • @Ryan 这是一个 winforms 应用吗?

标签: c# datagrid textbox datatable keypress


【解决方案1】:

尝试从以下位置更新您的代码:

if (e.KeyChar == 'L')
    {
        DBConnection.Open();
    }

 if (e.KeyChar == 'L')
    {
        e.Handled = true;
        DBConnection.Open();
    }

这应该会阻止事件传播和填充您的文本框。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 2014-01-10
    • 2013-12-06
    • 2012-10-24
    相关资源
    最近更新 更多