views:

308

answers:

2

I'm dynamically adding rows to a datagridview this way:

Question question = new Question();
List<Question> questions = question.GetQuestionsByQuestionnaire(questionnaireId);
if (questions != null)
{
    dgvQuestions.Columns.Add("Question", "Vraag");
    dgvQuestions.Columns.Add("QuestionType", "Vraag type");
    dgvQuestions.Columns.Add("Category", "Categorie");

    for (int i = 0; i < questions.Count; i++ )
    {
        int row = dgvQuestions.Rows.Add();

        dgvQuestions.Rows[row].Cells["Question"].Value = questions[i].Question;
        dgvQuestions.Rows[row].Cells["QuestionType"].Value = questions[i].QuestionType;
        dgvQuestions.Rows[row].Cells["Category"].Value = questions[i].Category;

        dgvQuestions.Rows[row].Tag = questions[i];
    }
}

I don't get any errors, but the cell value stays null and I'm 100% sure that Question, QuestionType and Category contains data. What am i missing here?

A: 

I'm not sure about why this is the case, but I'd go for a mix of dynamic data but typed dataset.

What you'd do is:

  1. Create a typed DataSet, add a "Questions" table with the columns you need
  2. Put an instance of your DataSet from the Toolbox on your form (must recompile before that), name it for example myDataSource.
  3. Put a BindingSource on your form, assign the myDataSource to the DataSource property and select your table for the DataMember property.
  4. Assign the binding source to the DataSource property of your DataGridView

Add data to the data source by using for example myDataSource.Questions.NewQuestionsRow() and myDataSource.Questions.AddQuestionsRow(...).

Thorsten Dittmar
Thnx, but what I want is to set the Tag property for each row. Otherwise I could use the BindingList as a datasource.
Martijn
A: 

I've just encountered something similar. You might want to make sure EnableViewState is set to True for your GridView.

Jesse C. Slicer