如何初始化不在数据库中的数据集表?

时间:2019-05-26 16:52:52

标签: c# ado.net dataset

我在不在数据库中的数据集中创建了一个表,我需要将数据设置到该表并将数据绑定到组合框,该怎么办?

        DataRowView drv = statusBindingSource.AddNew() as DataRowView;
        drv.Row["Value"] = 1;
        drv.Row["Name"] = "Active";
        statusBindingSource.EndEdit();

        statusBindingSource.Add(drv);

我无法将外部对象添加到此列表。

1 个答案:

答案 0 :(得分:0)

创建新的DataTable,将其填充数据并绑定到组合框。我没有包含DataSet或BindingSource。

    private void Form1_Load(object sender, EventArgs e)
    {
        CreateDataTable();
        cbo1.SelectedIndex = -1;
    }

    private void CreateDataTable()
    {
        //Create new DataTable
        DataTable dt = new DataTable();
        //Add colums with column name and datatype
        dt.Columns.Add("Value", Type.GetType("System.Int32"));
        dt.Columns.Add("Name", Type.GetType("System.String"));
        //Add data
        object[] data = { 1, "Active" };
        dt.Rows.Add(data);
        object[] data2 = { 2, "Passive" };
        dt.Rows.Add(data2);
        //Bind to combo box
        cbo1.DataSource = dt;
        cbo1.DisplayMember = "Name";
        cbo1.ValueMember = "Value";
    }

    private void Cbo1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        MessageBox.Show($"The display member is {((DataRowView)cbo1.SelectedItem)["Name"]}, The value member is {cbo1.SelectedValue}");
    }