开发者

Populate DataGridViewComboBoxColumn runtime

I have this problem: I have a datagridview that reads the data from a db and I wish, for an integer column use a combobox to choose some values... I modified the column using DataGridViewComboBoxColumn type and after, on the init of the form this:

DataTable dt = new DataTable("dtControlType");
dt.Columns.Add("f_Id");
dt.Columns.Add("f_Desc");
dt.Rows.Add(0, "none");
dt.Rows.Add(1, "value 1");
dt.Rows.Add(2, "value 2");
dt.Rows.Add(3, "value 3");

pControlType.DataSource = dt;
pControlType.DataPropertyName = "pControlType";
pControlType.DisplayMember = "f_Desc";
pControlType.ValueMember = "f_Id";

but when the program starts (after this code) this message appears: error http://www.ghiboz.info/shots/4a4fe5fd.p开发者_如何学运维ng


solved by myself: here is the solution:

public class HGrid
{
    public static void MakeComboBoxColumn(ref DataGridViewComboBoxColumn col, List<string> values)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("f_Id").DataType = typeof(Int32);
        dt.Columns[0].DataType = typeof(Int32);
        dt.Columns.Add("f_Desc");
        dt.Columns[1].DataType = typeof(string);


        for (int i = 0; i < values.Count; i++)
        {
            dt.Rows.Add(i, values[i]);
        }

        col.DataSource = dt;
        col.DisplayMember = dt.Columns[1].ColumnName;
        col.ValueMember = dt.Columns[0].ColumnName;
    }
}

and here is the usage:

List<string> lControlType = new List<string>();
lControlType.Add("Semplice");
lControlType.Add("Esteso");
HGrid.MakeComboBoxColumn(ref pControlType, lControlType);

I hope that will be useful for everyone!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜