سؤال

I have combo box that I fill with data from table in format "code : value"

Later I define it, for example like:

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

On that way I get in combo box "1:green","2:red" etc Now I want to select in combo value from data-grid. If I have column colors in witch I have "green" in other row "red" etc , when i click on row with red value in column colors, i need to show in combo text "2:red" i try with find string comand but that work only with Code(if i write 2 in column with colors i will get selected value in combo box,but if i write "red" i wold not.

Code that i currently using to try and get the color from the datagrid and select the right record in combobox:

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

Thanx

هل كانت مفيدة؟

المحلول

I don't understand the question quite well, but about finding a part of a string, you have multiple solutions here.

String.Split will separate your string into two, based on the ':' character:

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

You can also use String.IndexOf based on ":" to get the position of the color:

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

The "cleanest" way to do this to my tastes would be to implement a simple class to handle all of that:

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];
    }
}

نصائح أخرى

//First create a enum class

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

//Then use this command to fill your combobox whit the values of the enum

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

// After you have done this you can use this command to read out the value of the combobox

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

the string wil then be the selected value of the combobox. But lookout becaus the combobox index starts at 0 and not 1.

Hope it works :)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top