Я работал над формой, которая представляет некоторые конкретные элементы в представлении таблицы данных. Все было реализовано и работает правильно; тогда я решил что-то изменить. Мне нужно много разных версий этой конкретной формы, поэтому я создал базовую форму, из которой могут быть получены другие мои формы. Когда я реализую наследование этой базовой формы, данные будут перечислены в обратном порядке. Другими словами, до того, как я внес изменение, были перечислены столбцы (Номер вопроса, Отмечено для проверки, Отвечено), но по какой-либо причине данные указаны (Отвечено, Отмечено для проверки, Номер вопроса). Причина, по которой это имеет значение, заключается в том, что мой код предполагает, что номер вопроса - это первая строка, и эта информация используется для поиска и отображения этого конкретного вопроса.
Базовая форма выглядит следующим образом
public partial class DataFormBase : FormBase
{
/// <summary>
/// Initializes a new instance of the <see cref="DataFormBase"/> class.
/// </summary>
public DataFormBase()
{
InitializeComponent();
DrawGUI();
}
protected virtual void PopulateDataGrid() {}
protected virtual void dgvData_CellClick(object sender, DataGridViewCellEventArgs e){}
private void dgvData_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
dgvData.ClearSelection();
}
}
И реализация выглядит так
public partial class SessionReviewForm : Core.DataFormBase
{
public QuestionSessionForm ParentSession
{
get; set;
}
public Session Session
{
get; set;
}
public SessionPart SessionPart
{
get; set;
}
/// <summary>
/// Shows the dialog form.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="sessionPart">The session part.</param>
/// <param name="parent">The parent.</param>
/// <returns></returns>
public static DialogResult ShowDialogForm(Session session, SessionPart sessionPart, QuestionSessionForm parent)
{
// if any of the params are null get the hell out!
if (session == null || sessionPart == null || parent == null)
return DialogResult.None;
// create the new form, and populate its params
SessionReviewForm form = new SessionReviewForm()
{
Session = session,
SessionPart = sessionPart,
ParentSession = parent,
};
// populate the forms data grid
form.PopulateDataGrid();
form.Size = new System.Drawing.Size(400,400);
// show the form
return form.ShowDialog(parent);
}
/// <summary>
/// Populates the data grid with the required information
/// </summary>
/// <param name="instance">The instance for the w</param>
protected override void PopulateDataGrid()
{
// Get all of the questions that are marked for review
SessionQuestions questionsToDisplay = SessionPart.SessionQuestions.GetMarkedForReview();
// add to the list all of the questions that have not yet been answered
questionsToDisplay.AddRange(SessionPart.SessionQuestions.GetNotAnswered());
// create a list of objects for the data grid view
List<SessionReviewData> objectList = new List<SessionReviewData>();
// for each question in the session question list, populate a new member of
// the object list
foreach (SessionQuestion sq in questionsToDisplay)
{
SessionReviewData temp = new SessionReviewData
{
QuestionNumber = sq.Sequence + 1,
MarkedForReview = sq.MarkForReview,
IsAnswered = sq.IsAnswered
};
objectList.Add(temp);
}
// bind the data grid view to the object list
dgvData.DataSource = objectList;
// format the column headers so that they have a space between words
for (int i = 0; i < dgvData.Columns.Count; i++)
{
dgvData.Columns[i].HeaderText = Utilities.AddSpacesToSentence(dgvData.Columns[i].Name);
}
}
/// <summary>
/// Handles the CellClick event of the dgvQuestions control.
/// populates the parent form with the selected question
/// then closes the form.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Forms.DataGridViewCellEventArgs"/> instance containing the event data.</param>
protected override void dgvData_CellClick(object sender, DataGridViewCellEventArgs e)
{
// if the user selects the header column, then get out.
if (e.RowIndex == -1)
return;
// send the question data to the parentSession form to display the question
ParentSession.DisplayQuestionByIndex((int)(dgvData.Rows[e.RowIndex].Cells[0].Value) - 1);
// close this form
Close();
}
Решено:
Оказывается, Нарранж организовал алфавитную обработку моей внутренней структуры данных, и это привело к тому, что они были перечислены в неправильном порядке.