1

I want to have null values in my table when the user has left the textbox empty. I'm doing this with a array and a for loop:

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); 
    }
}

This should be working, but when I'm adding a questioncat and a question and load it into my datagrid, the new questioncat and question has not added to the database, only a new QuestionId. I think it is because I say countinput[i] = null, but I don't know how I could also say that the values need to be null if de textboxes are empty.

Presto
  • 888
  • 12
  • 30
  • have you tried to set value to DbNull.Value if countinput[i]==null ? (more info : https://stackoverflow.com/questions/4958379/what-is-the-difference-between-null-and-system-dbnull-value) – Xavave Nov 14 '18 at 10:41
  • What is the point of `countinput[i] = null`? Those fields are already null by initialization. – Henning Koehler Nov 14 '18 at 10:44
  • I think this is mainly a question about data binding, so it would help to know the design of the database table and how you set up the DataSet and TableAdapter. – Robin Bennett Nov 14 '18 at 10:45

1 Answers1

0

You don't need the countinput variable. Alter the for loop after the "both empty" check to

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

and then add the question with

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

Currently you are always entering null values, and ignoring the user input.

Henning Koehler
  • 2,456
  • 1
  • 16
  • 20