如何从简单的DataTable创建DataGridViewComboBoxColumn

时间:2011-07-03 17:22:22

标签: c# winforms datagridview datatable datasource

我创建用户控件,编辑,显示范围DataGridView。

我的用户控件采用DataTable

public static DataTable CreateDataTable()
{
    var myDataTable = new DataTable();

    DataColumn myDataColumn;

    myDataColumn = new DataColumn
    {
        DataType = Type.GetType("System.String"),
        ColumnName = "id",
        ReadOnly = true
    };
    myDataTable.Columns.Add(myDataColumn);

    myDataColumn = new DataColumn
    {
        DataType = Type.GetType("System.String"),
        ColumnName = "citys"
    };
    myDataTable.Columns.Add(myDataColumn);
    return myDataTable;
}

我将myDataTables设置为DataSource并且一切正常。

但我需要创建列城市DataGridViewComboBoxColumn。 怎么做?

2 个答案:

答案 0 :(得分:3)

试试这个

DataGridViewComboBoxColumn oCol = new DataGridViewComboBoxColumn();
oCol.Name = "cities";
oCol.DataSource = //your DataSource
myDataGridView.Columns.Add(oCol);

希望它有所帮助!

答案 1 :(得分:1)

尝试这种方式:

        DataTable table = CreateDataTable();
        foreach (DataColumn column in table.Columns)
        {
            dataGridView1.Columns.Add(column.ColumnName, column.ColumnName);
        }
        //there is you code too here.