如何在C#中的运行时更改DataGridVewComboBoxColumn的DataSource
本文关键字:DataGridVewComboBoxColumn DataSource 运行时 | 更新日期: 2023-09-27 18:28:26
我正在进行一个项目,该项目读取硬件配置xml文件,并根据协议类型和通道对其数据进行解析和排序,以便在两列网格视图中进行进一步修改。列1将通道名称作为DataGridViewTextBoxColumn保存,而列2设置为DataGridViewComboBoxColumn,用户应该能够从下拉列表中选择一个项,该项是从SQL数据库(通道类型)的查询生成的。
SQL数据库表本身有两列,如下所示:接口通道类型
"接口"列用作区分"通道类型"的键,如果它们是RS232、RS422、RS485等
当我填充DataGridView时,我将其排序为首先运行所有RS422通道列表,然后运行RS232列表等等。然而,要做到这一点,我需要能够更改ComboBoxColumn的DataSource,使其具有不同的查询,例如第一次"SELECT Channel_Type FROM Table1 WHERE Interface='RS422'"而第二次我需要跑步"SELECT Channel_Type FROM Table1 WHERE Interface='RS232'"
因此,在代码中,我有以下内容:
private void scanner()
{
//...code for parser that assembles a List<> ...
ChannelTypeColumn.DataSource = Populate("SELECT Channel_Type FROM Table1 WHERE Interface='RS422'");
ChannelTypeColumn.ValueMember = "Channel_Type";
ChannelTypeColumn.DisplayMember = ChannelTypeColumn.ValueMember;
for(int x = 0; x < ChannelRS422List.Count; x++)
{
RowDataBuffer[0] = ChannelRS422List.channel;
dgv.Rows.Add(RowDataBuffer);
}
ChannelTypeColumn.DataSource = Populate("SELECT Channel_Type FROM Table1 WHERE Interface='RS232'");
for(int x = 0; x < ChannelRS232List.Count; x++)
{
RowDataBuffer[0] = ChannelRS232List.channel;
dgv.Rows.Add(RowDataBuffer);
}
}
private DataTable Populate(string query)
{
SqlCommand command = new SqlCommand(query, connection);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
adapter.Fill(table);
return table;
}
不幸的是,我不知道如何正确地更改数据源,因为使用这些方法只会向我显示上一个数据源定义中的项目列表。
如有任何帮助和建议,我们将不胜感激!
谢谢!
经过多次尝试,我终于找到了解决这个问题的方法。我需要通过我需要的行的单元格来完成,而不是通过列来完成。
private void scanner()
{
//...code for parser that assembles a List<> ...
for(int x = 0; x < ChannelRS422List.Count; x++)
{
RowDataBuffer[0] = ChannelRS422List.channel;
dgv.Rows.Add(RowDataBuffer);
}
int rowCount = 0;
for (int row = 0; row < dgv.Rows.Count; row++)
{
DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)(dgv.Rows[row].Cells[1]);
cell.DataSource = Populate("SELECT Channel_Type FROM Table1 WHERE Interface='RS422'");
cell.ValueMember = "Channel_Type";
cell.DisplayMember = cell.ValueMember;
rowCount = row+1;
}
for(int x = 0; x < ChannelRS232List.Count; x++)
{
RowDataBuffer[0] = ChannelRS232List.channel;
dgv.Rows.Add(RowDataBuffer);
}
for (int row = rowCount; row < dgv.Rows.Count; row++)
{
DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)(dgv.Rows[row].Cells[1]);
cell.DataSource = Populate("SELECT Channel_Type FROM Table1 WHERE Interface='RS232'");
cell.ValueMember = "Channel_Type";
cell.DisplayMember = cell.ValueMember;
rowCount = row+1;
}
}