Link to home
Create AccountLog in
Avatar of Olukayode Oluwole
Olukayode OluwoleFlag for Canada

asked on

How can i get my comboBox selection to work properly without a message box

I have in my c# application a combo box from which i  select a record and then
use the split command to get then items in the combo  (See Screen with the Combo box Below)

User generated image
The problem i have is that ordinarily if i click on a record it show give me the last figure  exchange rate
in the exchange rate box.

What happen right no is that is i just click I dont get anything selected into the exchange rate box (see below)

User generated image
Now when i introduced the message box and just click ok after the messagebox comes up i get the required result

see screen below.

User generated image
Definitely i dont want my application to ship out with users having to Click ok on message box

How can i solve this problem.

There must be  a way to get the selection without  the message box

The detailed code is shown below:

[private void glTRANSCurrencyValue_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Setting index to 0 at form load ensure that script below is not processed during combo initial load
            if (this.glTRANSCurrencyValue.SelectedIndex != 0)
            {
                glTRANSExchrateValue.Text = "0";
                System.Data.DataRowView selected_row = glTRANSCurrencyValue.SelectedItem as System.Data.DataRowView;
                // Always use this TryParse to determin a selected value. Thencomment ou the Message Box once satisfied
                bool isNumeric;
                int i;
                string str = glTRANSCurrencyValue.SelectedText.ToString();
                isNumeric = int.TryParse(str, out i);
                MessageBox.Show("The value of i is " + i);   // Always uncomment this line to see how TryParse worked

                string phrase = glTRANSCurrencyValue.SelectedText.ToString();
                string[] words = phrase.Split(' ');
                int j = 0;
                foreach (var word in words)   // Always put cursor on words to determine content of each field field[1] ..... field[n]. Can also Use switch to get the fields
                {
                    j += 1;

                    switch (j)
                    {
                        case 3:
                           
                            break;
                        case 5:
                            string var2 = $"{ word}";
                            glTRANSExchrateValue.Text = var2;
                            break;

                    }

                }
            }
        }[/code]



Please Help

Olukay
Avatar of Lukasz Zielinski
Lukasz Zielinski
Flag of Poland image

Hi,

you do get selected record in "selected_row" variable but later it's not used.
if your exchange rate is field in database, you can use:
 glTRANSExchrateValue.Text = selected_row["name_of_field_with_exrate"].ToString();

other solution would be to connect your glTRANSExchrateValue textBox directly to database table, in this case you do not have to handle changing selection on glTRANSCurrencyValue.

Values will switch automatically
Avatar of Olukayode Oluwole

ASKER

I have tried your suggestion by doing the follwing

1. commented out the message Box

2. Put then new suggested line after the message box

I got an error

Please the Exchange rate table and error screen attached

User generated image
and the error screen below

User generated image

What is the solution to that error


Olukay
ok, if you look at properties of glTRANSExchrateValue component in section Data.DataBindings do you have it connected to your datasource?

ziolko.
EE.jpg
Ok Now I have the Data Binding Page for Currency ComboBox and ExchangeValue TextBox  (see below) as you requested.

User generated image

User generated image
Under ExchangeRate I could not find SelectedItem  and SelectedValue BUT it exist under

Currency Comboxbox. Which i can understand because i actually loaded Currency ComboBox

from the database


I tried to examine one of the field bindings and it was asking for a connection string so i stopped  and thought i should explain my situation before i make any changes.

Normally I connect to my local server  or a cloud server by changing parameters in my app.config file.

If I start specifying a connection string under data  bindings would I have to be changing this
setting each time i connect to either a local server or a cloud server.



Now that you know what i want and have the 2 pages on bindings please advise on what to do next

Thanks
Hi,

how do you load contents of your dropdown from DB?
do you query DB and run loop statement by adding items?

ziolko.
..my guess is that you run query and "manually" fill comboBox with some loop statement, if I'mright then indeed, this:
System.Data.DataRowView selected_row = glTRANSCurrencyValue.SelectedItem as System.Data.DataRowView;
will not work.

And yes it is true - setting bindings in design time will make it difficult to switch between local and remote databases.
But you can set them in run-time, something like this:

            comboBox1.DataSource = this.testtableBindingSource;
            comboBox1.DisplayMember = "FieldName1";

that's of course my sample for table called "testtable" that has field called "FieldName1"

in your case that will be probably something like:
this.exchratesBindingSource

you can do similar run-time binding with both your controls: comboBox (glTRANSCurrencyValue) and editBox (glTRANSExchrateValue)
if you do that - switching between comboBox items wil lautomatically update values in ex. rate editbox without any additional code

ziolko.
Below specifies how i do the load

1. At Form Load I have the script below

 glTRANSCurrencyValue.DataSource = GlobalConfig.Connection.GetExchRate_All();
 glTRANSCurrencyValue.DisplayMember = "FullCodeName";

2. That then goes into the section below to load the combo using while (reader.Read())  Loop

[public List<ExchRatesModel> GetExchRate_All()
        {
            List<ExchRatesModel> results = new List<ExchRatesModel>();

           

            using (var conn = new NpgsqlConnection(pgrstring))
            {
                using (var command = new NpgsqlCommand("public.spexchrates_getall", conn))
                {
                    conn.Open();
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.Add(new NpgsqlParameter("companycodex", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = ParameterDirection.Input, Value = LoginDetails.staticcompany });

                    var reader = command.ExecuteReader();
                    // Bring in Parameters to limit selection to Login.Staticcompany

                    while (reader.Read())
                    {
                        ExchRatesModel model = new ExchRatesModel();

                        //if ((string)reader["absecode"] != null)

                        if (((string)reader["mnthyear"] != null) && ((string)reader["othercurrencycode"] != null) && ((string)reader["ledgercurrencycode"] != null) && Convert.ToDecimal(reader["exchrate"]) != 0)
                        {
                            model.Id = (int)reader["id"]; //id is the column name in the database
                            model.mnthyear = (string)reader["mnthyear"]; //absecode is the column name in the database
                            model.othercurrencycode = (string)reader["othercurrencycode"]; //absedesc is the column name in the database
                            model.ledgercurrencycode = (string)reader["ledgercurrencycode"]; //absedesc is the column name in the database
                            model.exchrate = Convert.ToDecimal(reader["exchrate"]); //absedesc is the column name in the database
                            model.Companycode = (string)reader["companycode"]; //absedesc is the column name in the database
                            results.Add(model);
                        }
                    }
                }
            }
            return results;
        }[/code]


Any advise
I find this your statement interesting

you can do similar run-time binding with both your controls: comboBox (glTRANSCurrencyValue) and editBox (glTRANSExchrateValue)
if you do that - switching between comboBox items wil lautomatically update values in ex. rate editbox without any additional code

Do you have teamviewer and can you help on line real time


Thanks

Olukay
Hi,
you are almost there:)
The datasource you create by calling GetExchRate_All() must be also assigned to textBox… but it must be the same datasource.
To do so you need to introduce some global variable and initialize it with GetExchRate_All() method, then use this variable as datasource for both: comboBox and textBox.
Term "global variable" may not be strictly correct but I do not know exact structure of your project.

In my case I used private static on a form that I use in test project:
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private static List<ExchRatesModel> exDataSource;

now you have to initialize it and use, i used simple button, comboBox and editBox:

        private void button4_Click(object sender, EventArgs e)
        {
            exDataSource = GetExchRate_All();
            comboBox1.DataSource = exDataSource;
            comboBox1.DisplayMember = "FullCodeName";
            textBox2.DataBindings.Add(new System.Windows.Forms.Binding("Text", exDataSource, "exchrate", true));
     }

and make sure that code of private void glTRANSCurrencyValue_SelectedIndexChanged(object sender, EventArgs e) is commented (or removed) to make sure that nothing gets executed in this method.

I used button but you can simply replace:

 glTRANSCurrencyValue.DataSource = GlobalConfig.Connection.GetExchRate_All();
 glTRANSCurrencyValue.DisplayMember = "FullCodeName";

with this:

            exDataSource = GetExchRate_All();
            glTRANSCurrencyValue.DataSource = exDataSource;
            glTRANSCurrencyValue.DisplayMember = "FullCodeName";
            glTRANSExchrateValue.DataBindings.Add(new System.Windows.Forms.Binding("Text", exDataSource, "exchrate", true));


ziolko.
ASKER CERTIFIED SOLUTION
Avatar of Lukasz Zielinski
Lukasz Zielinski
Flag of Poland image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Worked like Magic

Thanks very much

Team viewer support not needed  for now


Olukay
I am sorry i had a similar problem while doing a similar data movment

between a combobox in a grid and a textbox within same Grid.

DataBinding is not defined for the Grid

Please  find attached the issue and help with the syntax

DataGridImplementation180220.docx


Olukay
if you use standard DataGridView component available on VisualStudio's Toolbox then you can simply use:
dgvtxtDivision.DataSource = LoginDetails.exDataSource2;

ziolko.
Yes I use the DataGridView in Visual Studio

dgvtxtDivision as a textbox as no Datasource  property

So i tried changing it to a combobox  to enable me have the DataSource property which i got (Though i really think

it should be a textbox so that once department is selected from combo it gets filled.

my code is now as below

LoginDetails.exDataSource2 = GlobalConfig.Connection.GetResponsibleMgr_All();
dgvcmbDepartment.DataSource = LoginDetails.exDataSource2;
dgvcmbDepartment.DisplayMember = "FullCodeName";
dgvcmbDepartment.ValueMember = "deptcode";
dgvtxtDivision.DataSource = LoginDetails.exDataSource2;

and my result  from the grid combo is shown below with division columnempty

User generated imagedgvtxtDivision.ValueMember = "divisioncode";

What am I doing wrongly

Regards


Olukay
if I remember correctly you have to assign DataPropertyName of a grid column

ziolko.
...and one more thing, on a grid column you have to assign .DataSource property but this cannot be your  LoginDetails.exDataSource2
it has to be list of unique values.

ziolko.
suggestion I gave you:
dgvtxtDivision.DataSource = LoginDetails.exDataSource2

was my mistake, I thought "dgvtxtDivision" was a grid not just a grid column

ziolko.
not sure what exactly you want to achieve but quick and easy solution is:
dgvtxtDivision.DataSource = LoginDetails.exDataSource2.Select(el => el.divisioncode).Distinct().ToList();

that's assuming you use LinQ

ziolko.