其他答案非常困难且容易出错。根据要求添加所需的单元格类型更容易。
例子:
使用设计器,创建一个带有 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, // questions can't be edited
};
}
创建答案单元格的方法有一个参数,指示所需的答案类型:
private DataGridViewCell CreateAnswerCell(AnswerType answerType)
{
// type of column depends on rowIndex
DataGridViewCell cell;
switch (answerType)
{
case AnswerType.YesNo: // Create a checkbox cell
cell = new DataGridViewCheckBoxCell()
{
ValueType = typeof(bool),
Value = false,
};
break;
case AnswerType.LoadFile: // Create a Button cell
cell = new DataGridViewButtonCell()
{
ValueType = typeof(string),
Value = "Load!",
};
break;
case AnswerType.Combo: // Create a Combo Cell
var selectableValues = Enumerable.Range(0, 4);
var comboItems = Enumerable.Range(0, 100);
cell = new DataGridViewComboBoxCell()
{
DataSource = new BindingList<int>(comboItems.ToList()),
};
break;
default: // Create a Text cell
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);
}
等等,走吧!简单的来吧您好!