C# datagridview setting cell value stays null
I'm dynamically addi开发者_如何学JAVAng 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?
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:
- Create a typed
DataSet
, add a "Questions" table with the columns you need - Put an instance of your
DataSet
from the Toolbox on your form (must recompile before that), name it for examplemyDataSource
. - Put a
BindingSource
on your form, assign themyDataSource
to theDataSource
property and select your table for theDataMember
property. - Assign the binding source to the
DataSource
property of yourDataGridView
Add data to the data source by using for example myDataSource.Questions.NewQuestionsRow()
and myDataSource.Questions.AddQuestionsRow(...)
.
I've just encountered something similar. You might want to make sure EnableViewState is set to True for your GridView.
Make sure VitualMode is set to False for your GridView.
精彩评论