【问题标题】:Find part off string in combo box在组合框中查找字符串的一部分
【发布时间】:2014-05-12 11:36:58
【问题描述】:

我有一个组合框,我用“代码:值”格式的表格中的数据填充

稍后我定义它,例如:

    this.cmdColor.DataSource = GetValuesForCombo("COLOR");
    this.cmdColor.DisplayMember = "DESCR";
    this.cmdColor.ValueMember = "CODE";
    this.cmdColor.SelectedIndex = -1;

这样我进入组合框“1:绿色”,“2:红色”等 现在我想从数据网格中选择组合值。如果我在女巫中有列颜色,我在其他行“红色”等中有“绿色”,当我单击列颜色中具有红色值的行时,我需要在组合文本“2:红色”中显示我尝试使用查找字符串命令但这仅适用于代码(如果我在颜色列中写 2,我将在组合框中获得选定的值,但如果我写“红色”,我不会。

我目前用来尝试从数据网格中获取颜色并在组合框中选择正确记录的代码:

cmdColor.SelectedIndex = CmdColor.FindString(grdColors.CurrentRow.Cells["COLORCELL"].Value.ToString()`);

感谢

【问题讨论】:

  • 您能否展示您当前用于尝试从数据网格中获取颜色并在您的组合框中选择正确记录的代码?
  • 是的,我当然编辑问题...

标签: c# combobox


【解决方案1】:

我不太了解这个问题,但是关于查找字符串的一部分,您在这里有多种解决方案。

String.Split 将根据 ':' 字符将您的字符串分成两部分:

string dataFromTable = "1:green";
string[] dataSplitted = dataFromTable.Split(new char[] { ':' });
// now dataSplitted[0] = "1" and dataSplitted[1] = "green";

也可以根据“:”使用String.IndexOf来获取颜色的位置:

// be sure that you actually have something after your ":", else it will
// throw an OutOfRange exception
string color = dataFromTable.Substring(dataFromTable.IndexOf(":") + 1);

按照我的口味,“最干净”的方法是实现一个简单的类来处理所有这些:

public class TableColor {
    int id;
    string color;

    public static char[] separator = new char[] { ':' };

    public TableColor(string data)
    {
        string[] dataSplitted = data.Split(separator);
        id = Convert.ToInt32(dataSplitted[0]);
        color = dataSplitted[1];
    }
}

【讨论】:

    【解决方案2】:

    //首先创建一个枚举类

    namespace DemoEnum
    {
        public enum Color
        {
            RED,
            YELLOW,
            GREEN,
            BLACK,
            ORANGE,
        }
    }
    

    //然后使用这个命令用枚举值填充你的组合框

    cmdColor.DataSource = Enum.GetNames(typeof(Color));
    

    // 完成此操作后,您可以使用该命令读出组合框的值

    "string" = Convert.ToString((Kleur)cmdColor.SelectedIndex);
    

    该字符串将成为组合框的选定值。但要小心,因为组合框索引从 0 开始,而不是 1。

    希望它有效:)

    【讨论】:

      猜你喜欢
      • 2021-05-01
      • 1970-01-01
      • 2016-02-24
      • 2013-12-19
      • 1970-01-01
      • 1970-01-01
      • 2011-04-14
      • 1970-01-01
      • 2020-05-17
      相关资源
      最近更新 更多