下拉列表引用多个数据表

时间:2013-03-20 22:17:22

标签: c# drop-down-menu datatable

我正在创建一个WMI程序,它将查询输出到数据表,然后输出到数据网格。我想创建一个历史记录下拉列表,将当前日期和时间作为项目,并将刚刚创建的数据表克隆为“值”。

选择下拉列表中的项目会将数据网格更改为此时运行的任何先前数据表。

到目前为止,这是代码,但我不确定如何将数据表添加为字符串或数组?

// copy current data table

DataTable cloneTable = new DataTable();
cloneTable = dt.Copy();

ddlEventhistory.Items.Add(new Data { 
    Name = DateTime.Now.ToString(), 
    Value = cloneTable () 
}); 
ddlEventhistory.DisplayMember = "Name";
ddlEventhistory.ValueMember = "Value";

更新1:这是我的自定义类:

 private class Data 
 { 
     public string Name { get; set; } 
     public Object Value { get; set; } 
 }

更新2:以下是我的下拉列表更改后的内容:

private void ddlEventhistory_SelectionChangeCommitted(object sender, EventArgs e)
{
    dgEvent.DataSource = (ddlEventhistory.SelectedValue as Data).Value as DataTable;                 
}

更新3:以下是最终代码

private class Data 
 { 
     public string Name { get; set; } 
     public Object Value { get; set; } 
 }

//History

        //take existing data table and copy it's source
        DataTable eventhistory = new DataTable();
        eventhistory = (DataTable)dgEvent.DataSource;

        ddlEventhistory.Items.Add(new Data { Name = DateTime.Now.ToString(), Value = eventhistory });
        ddlEventhistory.DisplayMember = "Name";
        ddlEventhistory.ValueMember = "Value";

//when drop down list selection is changed do....

private void ddlEventhistory_SelectionChangeCommitted(object sender, EventArgs e)
    {
        // Assign DataTable of selected ComboBox item to DataGrid.
       dgEvent.DataSource = (ddlEventhistory.SelectedItem as Data).Value as DataTable;
    }

1 个答案:

答案 0 :(得分:0)

您可以将数据副本添加到您的Combobox项目中。

//copy current data table
DataTable cloneTable = dt.Copy();

ddlEventhistory.Items.Add(new Data { Name = DateTime.Now.ToString(), Value = cloneTable }); 
ddlEventhistory.DisplayMember = "Name";
ddlEventhistory.ValueMember = "Value";

然后,当用户选择其中一个项目时,您可以在这样的DataGrid中显示它。

private void ddlEventhistory_SelectionChangeCommitted(object sender, EventArgs e)
{
    // Assign DataTable of selected ComboBox item to DataGrid.
    dgEvent.DataSource = (ddlEventhistory.SelectedItem as Data).Value as DataTable;
}