【问题标题】:Prevent query insertion when there is no data to be inserted在没有要插入的数据时阻止查询插入
【发布时间】:2012-09-05 05:12:42
【问题描述】:

我正在使用 C# 和 SQL Server CE,我的问题是:

  1. 在我的 WinForms 应用程序中,我有几个要填充数据的文本框。我想知道在没有填充文本框的情况下如何防止插入时出现用户错误?

  2. 如何判断文本框中何时没有数据用于查询插入?

这是我的代码:

koneksi.Open();
int query = perintahsql.ExecuteNonQuery();
try
{
    if (query > 0)
    {
        MessageBox.Show("Success.");
    }
    else
    {
        MessageBox.Show("Can't insert record because of empty(s) field.");
        perintahsql.Cancel();
    }
}
catch(Exception ex)
{
    MessageBox.Show(ex.ToString(), "Can't insert record!");
    perintahsql.Parameters.Clear();
}
koneksi.Close();

【问题讨论】:

  • 你能检查你得到query返回值是> 0吗?您可以在插入文本框之前检查是否有值或也不

标签: c# sql-server-ce


【解决方案1】:

在将数据插入数据库中之前,您需要为您运行的文本字段提供一种验证方法,因此您可以根据需要使用更多方法。例如:

Control Validation

writing your own validating routine

使用validation libraries

【讨论】:

    【解决方案2】:

    如果它适合您,请尝试此解决方案。

    private bool ReadyToInsert()
    {
        bool isOk = true;
        TextBox[] arrText = new TextBox[] { textBox1, textBox2, textBox3 };
    
        foreach (TextBox i in arrText)
        {
            if (i.Text.Trim().Length == 0)
            {
                isOk = false;
            }
        }
        return isOk;
    }
    

    这是一个检查表单中所有文本框的函数。在尝试插入记录之前调用此函数。

    用法:类似这样的

    // other codes here
    if (ReadyToInsert)
    {
        // call insert method here
    }
    else
    {
        MessageBox.Show("Can't insert record because of empty(s) field.");
    }
    

    【讨论】:

    • 谢谢,我试过你的代码,但它仍然显示设置为自动递增的主键,你知道吗?
    • 什么primary key?直到现在,您还没有在问题上指定这一点。你现在遇到了什么错误@RadityaKurnianto?
    • 其实我有几个文本框和组合框,用户需要填写这些控件,但是当我尝试将其留空时,我设置为自动递增的主键值总是成功插入在查询中。
    猜你喜欢
    • 2015-07-07
    • 2014-11-26
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多