views:

55

answers:

3

Using C# & MySQL

When i select a particular value from the combobox then i clicked the button, the corresponding value should display in the other textbox

code

protected void Button1_Click(object sender, EventArgs e)
    {
        cmd2 = new OdbcCommand("Select name from users where username = '" + combobox1.Text  + "' ", con);
        dr1 = cmd2.ExecuteReader();
        while (dr1.Read())
        {
            textbox1.Text = dr1.GetString(0);

        }
        dr1.Close();

    }

The Above Code is working, but nothing displaying in Textbox1, there is the problem only in the query, I changed the query like Select name from users where username = '005' Output is displaying in the textbox1, but when i used combobox value it is not displaying.

I also tried:

combobox1.text, combobox1.selectedvalue, combobox1.selecteditem, combobox1.selectedindex

Combobox Filling Code

cmd2 = new OdbcCommand("Select username from users, con);
        ada2 = new OdbcDataAdapter(cmd2);
        ada2.Fill(data2);
        combobox1.DataValueField = "username";
        combobox1.DataSource = data2;

combobox1.DataBind();

Username values like 201, 202, 203....,

Why is the query executing while using the combobox value....

Need Query Help

+1  A: 

comboBox1.Items[comboBox1.SelectedIndex].Text should give you what you want.


wrap your combo box's filling code in

if (!Page.IsPostBack) {}

It should be filled only when the page is loaded the first time and not on subsequent postbacks otherwise it will reset the binding everytime the page is posted back.

decyclone
make sure that value of SelectedIndex is >= 0 to avoid out of index exceptions.
decyclone
Same Result am getting by using your query....,
Gopal
Ok, how do you fill your ComboBox? Can you post some code?
decyclone
I added the combobox filling code.....
Gopal
Have you set you `DrowDownList`'s `AutoPostBack` property to `True`?
decyclone
If i used the AutoPostBack = true, the combobox value displaying from the first value, it is not displaying a selected value.....
Gopal
When i clicked the Button, the combobox value is displaying from the first value, it is not displaying a selected value, what is the problem in my webpage....
Gopal
have you tried using both `comboBox1.Items[comboBox1.SelectedIndex].Text` and `comboBox1.Items[comboBox1.SelectedIndex].Value`?
decyclone
Same Result, ooh how to solve this simple issue, i am facing big headache...
Gopal
See my latest edit.
decyclone
+1  A: 

you should use combobox1.SelectedItem.Text for the desired result.

Azhar
+1  A: 

if you are using winform controls, please use below code

comboBox1.DataSource = list;
 comboBox1.ValueMember = "Name";

to get value from combobox use comboBox1.SelectedValue[It will return object type]

Venkat