I created a database and wrote functions that should take column names from tables and put them in DataGridViewComboBoxCells. However, after running the program, no errors came out, but all ComboBoxCells are empty
I created a function that accesses the database, takes the column names from there and returns a dictionary:
public Dictionary<int, List<string>> GetDisciplinesHeaders(string connectionString, string tableName)
{
Dictionary<int, List<string>> headers = new Dictionary<int, List<string>>();
try
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
string query = $"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{tableName}' AND COLUMN_NAME != 'Class'";
using (OleDbCommand command = new OleDbCommand(query, connection))
{
using (OleDbDataReader reader = command.ExecuteReader())
{
int classNumber = 1; // Начинаем с первого класса
while (reader.Read())
{
if (!headers.ContainsKey(classNumber)) {
headers[classNumber] = new List<string>();
}
headers[classNumber].Add(reader.GetString(0));
classNumber++;
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Ошибка: " + ex.Message);
}
return headers;
}
Created a function that renders a DataGridView with a Datagridviewcomboboxcell inside:
private DataGridView CreateDataGridView()
{
DataGridView dataGridView = new DataGridView();
dataGridView.Dock = DockStyle.Fill;
DataGridViewTextBoxColumn rowNumerColumn = new DataGridViewTextBoxColumn();
rowNumerColumn.HeaderText = "#";
dataGridView.Columns.Add(rowNumerColumn);
for (int i = 0; i < 12; i++)
{
if (i % 2 == 0)
{
DataGridViewComboBoxColumn subjectColumn = new DataGridViewComboBoxColumn();
subjectColumn.HeaderText = $"Класс {i / 2 + 1} Дисциплины";
dataGridView.Columns.Add(subjectColumn);
// Проверяем номер класса и выбираем соответствующую таблицу
string tableName;
if (i + 1 >= 1 && i + 1 <= 4)
tableName = "Disciplines1_4";
else if (i + 1 >= 5 && i + 1 <= 9)
tableName = "Disciplines5_9";
else
tableName = "Disciplines10_11";
// Получаем названия полей из таблицы и заполняем ComboBox
Dictionary<int, List<string>> headers = GetDisciplinesHeaders(connectString, tableName);
if (headers.ContainsKey(i / 2 + 1))
{
foreach (string header in headers[i / 2 + 1])
{
subjectColumn.Items.Add(header);
}
}
}
else
{
DataGridViewTextBoxColumn roomColumn = new DataGridViewTextBoxColumn();
roomColumn.HeaderText = "кабинет";
dataGridView.Columns.Add(roomColumn);
}
}
// Остальной код обработки событий и т.д.
return dataGridView;
}
GHOSTof TIME is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.