首页 > 解决方案 > 如果文本框为空,则数据库中的自动空值

问题描述

null values当用户离开时,我想在我的桌子上textbox放空。我用一个数组和一个for循环来做这个:

private void AddQuestion()
{
    string [] checkinput= new string[] { txtBxQuestionCat.Text, txBxQuestion.Text }; 
    string[] countinput= new string[2]; 

    if (String.IsNullOrEmpty(txtBxQuestionCat.Text) && String.IsNullOrEmpty(txBxQuestion.Text))

    {   
        ExceptiesException ex = new ExceptiesException("error");
        throw ex;
    }

    for (int i = 0; i < countinput.Length; i++) 
    {
        if (checkinput[i] == "") 
        {
            countinput[i] = null; 
        }
    }

    try
    {   
        qa = new HR5DataSetTableAdapters.QueriesTableAdapter();
        qa.AddQuestion(countinput[0], countinput[1]);


        hR5DataSetQuestionTableAdapter.Fill(hR5DataSet.question);

        questionViewSource1.View.MoveCurrentToLast();
        MessageBox.Show("add complete");
    }
    catch (SqlException ex) 
    {
        MessageBox.Show(ex.Message); 
    }
}

这应该可以工作,但是当我添加 aquestioncat和 aquestion并将其加载到 mydatagrid中时,新的questioncatquestion没有添加到数据库中,只有一个新的QuestionId. 我认为这是因为我说countinput[i] = null,但我不知道null如果 detextboxes为空,我怎么能说这些值需要是。

标签: c#sqlarraysdatabase

解决方案


你不需要这个countinput变量。在“都为空”检查后将 for 循环更改为

for (int i = 0; i < checkinput.Length; i++) 
    if (checkinput[i] == "") 
        checkinput[i] = null; 

然后添加问题

qa.AddQuestion(checkinput[0], checkinput[1]);

目前,您总是输入空值,而忽略用户输入。


推荐阅读