【问题标题】:Adding data to a dataGridView row in which there is already a comboboxcolumn将数据添加到已存在组合框列的 dataGridView 行
【发布时间】:2012-12-07 19:14:46
【问题描述】:

我有一个DataGridView,它在运行时填充了几个ComboBoxColumn 列。例如,

var newCountryColumn = new DataGridViewComboBoxColumn();
newCountryColumn.HeaderText = "Country";
newCountryColumn.DataSource = CountryListArray.ToArray();
newCountryColumn.DisplayMember = "Name";
newCountryColumn.ValueMember = "Code";

等等。现在,在运行时,用户选择要打开的文件,然后将其逐行解析成一个数组。

var lines = File.ReadAllLines(path + "\\" + choosenFile);
foreach (string line in lines) {
    numOfRecords++;
    errorCounter = 0;
    string[] items = line.Split('\t').ToArray();

    int billState = headerIndex[0] - 1;
    int billCountry = headerIndex[1] - 1;
    int shipState = headerIndex[2] - 1;
    int shipCountry = headerIndex[3] - 1;

    for (int i = 0; i < headerIndex.Count; i++) {
        int index = headerIndex[i];
        /*Get the state and country codes from the files using the correct indices*/
        Globals.Code = items[index - 1].ToUpper();
        //If the code can't be found in either list
        if (!CountryList.ContainsKey(Globals.Code) && !StateList.ContainsKey(Globals.Code)) {
            errorCounter++;
            if (errorCounter == 1){
                dataGridView1.Rows.Add(items);
            }
        }
    }
}

现在,效果很好,除了当我在DataGridView 中滚动到组合框所在的位置时。显然,代码不喜欢将 items 数组中的值添加到预先存在的组合框列中。我得到一个错误对话框:

DataGridView 出现以下异常:System.ArguementException: DataGridViewComboBoxCell value is not valid.

items 数组中的项目可以显示在组合框列中吗?

【问题讨论】:

    标签: c# datagridview datagridcomboboxcolumn


    【解决方案1】:
    newCountryColumn.DisplayMember = "Name";
    newCountryColumn.ValueMember = "Code";
    

    告诉newCountryColumn.DataSource 期待一个包含名为NameCode 的属性的集合。但是您将其传递给string[]。那是错误的,这就是错误消息告诉您的内容。

    有几种方法可以做到这一点,最直接的方法是使用属性NameCode 声明您自己的类:

    class CountryTuple
    {
        public string Code { get; private set; }
        public string Name { get; private set; }
    
        public CountryTuple(string code, string name)
        {
            this.Code = code;
            this.Name = name;
        }
    }
    

    现在您可以实例化您的集合了:

    var cts = new List<CountryTuple>();
    

    将实例添加到您的集合中::

    cts.Add(new CountryTuple(items[index - 1].ToUpper(), whatever));
    

    并将其分配给您的DataSource

    newCountryColumn.DataSource = cts;
    

    【讨论】:

      猜你喜欢
      • 2014-09-11
      • 2016-10-29
      • 2017-05-27
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多