C# 在组合框中查找字符串的部分
我有一个组合框,用“code:value”格式的表中的数据填充 后来我定义了它,例如:C# 在组合框中查找字符串的部分,c#,combobox,C#,Combobox,我有一个组合框,用“code:value”格式的表中的数据填充 后来我定义了它,例如: this.cmdColor.DataSource = GetValuesForCombo("COLOR"); this.cmdColor.DisplayMember = "DESCR"; this.cmdColor.ValueMember = "CODE"; this.cmdColor.SelectedIndex = -1; 这样我就进入了组合框“1:绿色”、“2:红色”等等
this.cmdColor.DataSource = GetValuesForCombo("COLOR");
this.cmdColor.DisplayMember = "DESCR";
this.cmdColor.ValueMember = "CODE";
this.cmdColor.SelectedIndex = -1;
这样我就进入了组合框“1:绿色”、“2:红色”等等
现在我想从数据网格中选择组合值。如果我有列颜色,我在其他行中有“绿色”的“红色”等,当我点击列颜色中有红色值的行时,我需要在组合文本中显示“2:red”,我尝试查找字符串comand,但这只适用于代码(如果我在列中用颜色写2,我将在组合框中获得所选值,但如果我写“red”,我不会
我当前用于尝试从datagrid获取颜色并在combobox中选择正确记录的代码:
cmdColor.SelectedIndex = CmdColor.FindString(grdColors.CurrentRow.Cells["COLORCELL"].Value.ToString()`);
Thanx我不太理解这个问题,但是关于查找字符串的一部分,这里有多种解决方案 将根据“:”字符将字符串一分为二:
string dataFromTable = "1:green";
string[] dataSplitted = dataFromTable.Split(new char[] { ':' });
// now dataSplitted[0] = "1" and dataSplitted[1] = "green";
您还可以使用“基于”:“获取颜色的位置:
// 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];
}
}
//首先创建一个枚举类
namespace DemoEnum
{
public enum Color
{
RED,
YELLOW,
GREEN,
BLACK,
ORANGE,
}
}
//然后使用此命令用枚举值填充组合框
cmdColor.DataSource = Enum.GetNames(typeof(Color));
//完成此操作后,可以使用此命令读取combobox的值
"string" = Convert.ToString((Kleur)cmdColor.SelectedIndex);
然后字符串将成为组合框的选定值。但要注意,因为组合框索引从0开始,而不是从1开始
希望它能起作用:)你能显示你目前用来从数据网格中获取颜色的代码,并在组合框中选择正确的记录吗?当然可以,我编辑问题。。。