其他答案太复杂且容易出错。
按要求添加所需的单元格类型更加简单。
示例:
使用设计器创建一个带有DataGridView和两列的表单:一个用于问题,一个用于答案。
private DataGridView dataGridView3;
private DataGridViewTextBoxColumn columnQuestion;
private DataGridViewTextBoxColumn columnAnswer;
在我的班级中,我创建了用于答案类型的枚举
public enum AnswerType
{
Text,
YesNo,
LoadFile,
Combo,
};
我将创建两种方法:一种用于创建包含问题的单元格,另一种用于创建符合答案格式的单元格。
创建问题单元格的方法很简单:
private DataGridViewCell CreateQuestionCell(string question)
{
return new DataGridViewTextBoxCell()
{
ValueType = typeof(string),
Value = question,
ReadOnly = true,
};
}
创建答案单元格的方法有一个参数,用于指定所需的答案类型:
private DataGridViewCell CreateAnswerCell(AnswerType answerType)
{
DataGridViewCell cell;
switch (answerType)
{
case AnswerType.YesNo:
cell = new DataGridViewCheckBoxCell()
{
ValueType = typeof(bool),
Value = false,
};
break;
case AnswerType.LoadFile:
cell = new DataGridViewButtonCell()
{
ValueType = typeof(string),
Value = "Load!",
};
break;
case AnswerType.Combo:
var selectableValues = Enumerable.Range(0, 4);
var comboItems = Enumerable.Range(0, 100);
cell = new DataGridViewComboBoxCell()
{
DataSource = new BindingList<int>(comboItems.ToList()),
};
break;
default:
cell = new DataGridViewTextBoxCell()
{
ValueType = typeof(string),
Value = "<please enter name>",
};
break;
}
return cell;
}
当请求添加一行时,包含一个问题单元格和一个答案单元格:
private void AddRow(string question, AnswerType answerType)
{
DataGridViewRow row = new DataGridViewRow();
row.Cells.Add(this.CreateQuestionCell(question));
row.Cells.Add(this.CreateAnswerCell(answerType));
this.dataGridView1.Rows.Add(row);
}
为了测试,我创建了四个按钮和处理程序来添加行:
private Button buttonCheckbox;
private Button buttonAction;
private Button buttonCombo;
private Button buttonText;
private void OnButtonCheckbox(object sender, EventArgs e)
{
this.AddRow("Do you smoke", AnswerType.YesNo);
}
private void OnButtonText(object sender, EventArgs e)
{
this.AddRow("Name", AnswerType.Text);
}
private void OnButtonCombo(object sender, EventArgs e)
{
this.AddRow("Age?", AnswerType.Combo);
}
private void OnButtonAction(object sender, EventArgs e)
{
this.AddRow("Document upload", AnswerType.LoadFile);
}
现在,它已经可以运行了!就像打招呼一样简单!