3

選択したアイテムをコンボボックスから取得しようとしていますが、機能させることができません。

Form1 form = new Form1();
string cpuCount = form.comboBox1.SelectedItem.ToString();

さて、これは何も返していません。しかし、このコードを自分のに挿入するInitializeComponent()と、インデックス= 3のアイテムが選択され、その適切なアイテムが返されます。

comboBox1.SelectedIndex = 3;

なぜこのように動作するのですか?たとえば、インデックス= 5のアイテムを選択した場合でも、選択したアイテムはインデックス=3のアイテムであると見なされます。

----------コードがどのように見えるかを示すために拡張する必要があると思います。

Form1-すべてのアイテムをコンボボックスに追加します。

public partial class Form1 : Form
{
    Profile profile = new Profile();
    public Form1()
    {
        InitializeComponent();
        Profile profile = new Profile();
        string[] prof = profile.getProfiles();
        foreach (var item in prof)
        {
            comboBox5.Items.Add(Path.GetFileNameWithoutExtension(item));
        }

        int ram = 1024;
        for (int i = 0; i < 7; i++)
        {
            comboBox4.Items.Add(ram + " GB");
            ram = ram * 2;
        }

        int vram = 512;
        string size;
        for (int i = 0; i < 5; i++)
        {
            if(vram > 1000)
            {
                size = " GB";
            }
            else
            {
                size = " MB";
            }
            comboBox2.Items.Add(vram + size);
            vram = vram * 2;
        }

        for (int i = 1; i < 5; i++)
        {
            comboBox1.Items.Add(i * 2);
        }

        for (int i = 0; i < 5; i++)
        {
            comboBox3.Items.Add(i * 2);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string current = profile.currentProfile();
            profile.saveProfile(current);
        }

    }

つまり、button3は私の「保存」ボタンです。そして、これが私の「プロフィール」クラスです

class Profile
{
    public string folder { get; set; }
    public Profile()
    {
        this.folder = "Profiles";
        if (!File.Exists(folder))
        {
            Directory.CreateDirectory(folder);
            File.Create(folder + "/default.cfg").Close();
        }
    }

    public string[] getProfiles()
    {
        string[] files = Directory.GetFiles(folder);
        return files;
    }

    public void saveProfile(string filename)
    {
        Form1 form = new Form1();
        string cpuCount = "cpuCount=" + form.comboBox1.SelectedItem;
        string RAM = "maxRAM=" + form.comboBox4.SelectedItem;
        string VRAM = "maxVRAM=" + form.comboBox2.SelectedItem;
        string threads = "cpuThreads=" + form.comboBox3.SelectedItem;
        string path = folder + "/" + filename;
        StreamWriter sw = new StreamWriter(path);
        string[] lines = { cpuCount, RAM, VRAM, threads };

        foreach (var item in lines)
        {
            sw.WriteLine(item);
        }



        sw.Close();

    }

    public string currentProfile()
    {
        Form1 form = new Form1();
        string selected = form.comboBox5.SelectedValue + ".cfg".ToString();
        return selected;
    }
}

ありがとうございました。

4

4 に答える 4

3

私が見ることができることから、あなたはform.comboBox1.SelectedItem.ToString()の作成の直後に呼んでいますForm1。これはcpuCount、フォームが作成された直後、つまりマウスで選択したアイテムを変更する前に、変数が初期化されることを意味します。

SelectedIndexChanged変更後にコンボボックスの値を取得する場合は、イベントを使用できます。

于 2013-03-25T12:15:44.787 に答える
3

問題は、で何も選択されていないことですComboBox。フォームを作成してから、以前のユーザーインタラクションなしSelectedItemで、その時点でnullであるを取得する必要があります。

ComboBoxコントロールを作成してアイテムで埋める場合、SelectedItemプロパティはnull、プログラムで設定するか(たとえば、を使用してcomboBox1.SelectedIndex = 3)、ユーザーがコントロールを操作するまで続きます。この場合、上記のいずれも実行していないため、上記のエラーが発生します。

編集編集した質問に基づいて次のようにコードを変更します。最初にsaveProfileメソッドを変更して、テキストファイルに書き込んだ4つの文字列を渡すことができるようにします。または、フォームの参照を渡すこともできますが、それはお勧めしません。したがって、次のように方法を変更します。

public void saveProfile(string filename, string cpuCount, string RAM , string VRAM , string threads)
    {
        string path = folder + "/" + filename;
        using(StreamWriter sw = new StreamWriter(path)) 
        {
             sw.WriteLine("cpuCount=" + cpuCount);
             sw.WriteLine("maxRAM=" + RAM );
             sw.WriteLine("maxVRAM=" + VRAM );
             sw.WriteLine("cpuThreads=" + threads);
        }        
    }

次に、button3から呼び出します。次のようなイベントハンドラをクリックします。

private void button3_Click(object sender, EventArgs e)
{
            string current = profile.currentProfile();
            string cpuCount = this.comboBox1.SelectedItem.ToString();
            string RAM =  this.comboBox4.SelectedItem.ToString();
            string VRAM = this.comboBox2.SelectedItem.ToString();
            string threads = this.comboBox3.SelectedItem().ToString();
            profile.saveProfile(current, cpuCount, RAM, VRAM, threads);
}

または代わりに

private void button3_Click(object sender, EventArgs e)
{
            string current = profile.currentProfile();
            profile.saveProfile(current, this.comboBox1.SelectedItem.ToString(), this.comboBox4.SelectedItem.ToString(), this.comboBox2.SelectedItem.ToString(), this.comboBox3.SelectedItem().ToString());
}
于 2013-03-25T12:16:42.517 に答える
2

まず、Form_Loadイベントを追加し、コードをハンドラーに配置します。(プロパティの初期化およびその他の変数の初期化にはコンストラクターを使用します)

private void Form1_Load(object sender, EventArgs e)
{
this.comboBox1.SelectedItem= 5; // This will set the combo box to index 5
string cpuCount = this.comboBox1.SelectedText; // This will get the text of the selected item
}

したがって、変数のインデックス5にあるアイテムの値を取得し cpuCountます。

このselected句は、何かを選択した後の値を提供します。デフォルトでは(アプリを実行するとき)、comoboBoxには何も選択されていないため、値はnullとして表示されます。アイテムを選択すると、コンボボックスのselectedItem、selectedIndexを使用できます。 、selectedTextおよびselectedValueプロパティ。

データバインディングを使用してコンボボックスにアイテムを表示することもできます。これは、アイテムを手動で追加するよりも優れた方法です。

使用できるコンボボックスをデータバインドするには、

// Bind your combobox to a datasource, datasource can be a from a database table, List, Dataset, etc..

 IDictionary<int, string> comboDictionary = new Dictionary<int, string>();
            comboDictionary.Add(1, "first");
            comboDictionary.Add(2, "second");
            comboDictionary.Add(3, "third");
            comboBox1.DataSource = comboDictionary;
            comboBox1.DisplayMember = "Key";
            comboBox1.ValueMember = "Value";

// 

そしてここで、combobox1.SelectedIndexを使用して、データソース内のアイテムコレクションを調べることができます:)。combobox1.SelectedValueを使用すると、キーに対する値が提供されます。お役に立てれば。

于 2013-03-25T12:35:51.370 に答える
0

ComoboBoxにはアイテムが含まれていません。そのため、正しく戻りません。フォームオブジェクトを作成した後、コンボボックスで選択された値の権限にアクセスしています。

また、comboBoxにアイテムがある場合は、何も選択されていません。デフォルトでは、comboBoxでは何も選択されていません。あなたはそれを設定する必要があります。これを使って。それは何を返しますか?comboBox.SelectedIndexを設定してから、selectedItemを取得します。

int selectedIndex = form.comboBox1.SelectedIndex;

これを試して。ComboBoxにいくつかのアイテムを追加してから、selectedItemを取得します。

Form1 form = new Form1();
form.comboBox1.Add("Item 1");
form.comboBox1.Add("Item 2");
form.comboBox1.Add("Item 3");
form.comboBox1.SelectedIndex = 1;
string cpuCount = form.comboBox1.SelectedItem.ToString();
于 2013-03-25T12:17:49.407 に答える