0

コンボボックスにvalueMemberがあり、この値を整数に保存する必要があります...これは私のコードです:

public class Benzinky
{
   public int B_cislo { get; set; }
   public string Benzinka { get; set; }
}

var lines = File.ReadAllLines(@"C:...\pokus.txt");
var data = lines.Select(l => l.Split());
List<Benzinky> allB = data.Where(arr => arr.Length >= 2
                               && arr[1].Trim().All(Char.IsDigit))
                           .Select(arr =>
                              new Benzinky
                              {
                                 Benzinka = arr[0].Trim(),
                                 B_cislo = int.Parse(arr[1].Trim())
                              })
                           .ToList();
var bindingSourceB = new BindingSource();
bindingSourceB.DataSource = allB;
comboBox1.DataSource = bindingSourceB;
comboBox1.ValueMember = "B_cislo";
comboBox1.DisplayMember = "Benzinka";

私のtxt:

Prague 3106
Berlin 3107
........

何かアイデアはありますか?

4

2 に答える 2

3

ValueMemberコンボボックスSelectedValueの値を決定するためにのみ使用されます。の一部を取得するには、基になるアイテム (例では型です) を正しい型にキャストし、いくつかのプロパティから目的の値を取得する必要があります。基になるデータ型がわかっている場合の方法は次のとおりです。そして事前に:valueMemberComboBox itemBenzinkyvalueMember

int x = ((Benzinky) comboBox1.Items[index]).B_cislo;
//or using dynamic
dynamic item = comboBox1.Items[index];
int x = item.B_cislo;

ただし、何か動的なものが必要な場合 (あるvalueMember時点でプログラムによって変更される可能性がある場合に発生します)、次のように使用する必要がありますReflection

object item = comboBox1.Items[index];
var x = (int) item.GetType().GetProperty(comboBox1.ValueMember)
                            .GetValue(item, null);

:ただし、このアプローチは、コンボボックスの が のようなクラスではないReflection場合にのみ適用できます。これは、 a がそのプロパティとしてではなく、その下にあるアイテムが aであり、その場合、リフレクション コードが失敗するためです。DataSourceDataTableDataTableColumn nameValueMemberDataRowView

于 2013-11-06T16:08:07.597 に答える
3

omboBox1valueMemberを整数に変換し、結果を に格納する必要がありNumberます。これは複数の方法で実行できます。次を使用できますConvert.ToInt32();Int32.Parse()Int32.TryParse()

Int32.Parse

Number = Int32.Parse(comboBox1.ValueMember);

上記のコードはトリックを実行するはずですが、文字列に整数に解析できる値が含まれていない場合に問題が発生し、例外がスローされます。

Int32.TryParse例外の代わりに bool 値を返したい場合に使用できます。

Int32.TryParse

int Number;
bool result = Int32.TryParse(comboBox1.ValueMember, out Number);
if (result)
{
   Console.WriteLine("Converted '{0}' to {1}.", comboBox1.ValueMember, Number);         
}
else
{
  //conversion failed
  //Int32.Parse, would throw a formatexception here.
}

次のコードを試していただけますか:

comboBox1.DataSource = bindingSourceB;
comboBox1.ValueMember = "B_cislo";
comboBox1.DisplayMember = "Benzinka";
int Number;
if(Int32.TryParse(comboBox1.ValueMember, out Number))
{
  //Conversion succeeded
}
else
{
  //Conversion failed, you should send a message to the user
  //Or fill Number with a default value, your choice.
}

ソース:

MSDN Int32.Parse

MSDN Int32.TryParse

于 2013-11-06T14:55:04.940 に答える