简体   繁体   中英

Display database values in textbox

I have a datatable with 2 columns, ID and Name , I have populated my combobox with the column ID.

string Query = "SELECT * FROM [Database]";
OleDbConnection me = new OleDbConnection(connection);
OleDbCommand constr = new OleDbCommand(Query, me);
me.Open();
OleDbDataReader reader = constr.ExecuteReader();    
while(reader.Read())
{
     textBox15.Text = (reader["Name"].ToString());   
}   
reader.Close();

When I select an item from the combobox, I want to retrieve values from the Column Name in the same row. For instance I select a value from my combobox which is in datarow 1 and it matches the datarow 1 in the table Name

Is there anyway to do this?


I am currently here

{
string Query = "SELECT * FROM [Database] where Name ='" + comboBox6.Text + "' ";              string y = textBox15.Text
                OleDbConnection me = new OleDbConnection(connection);
                OleDbCommand constr = new OleDbCommand(Query, me);

                me.Open();
                OleDbDataReader reader = constr.ExecuteReader();
                constr.Parameters.Add(new OleDbParameter("@Name", y));


                while (reader.Read())
                {
                  textBox15.Text = reader["Name"].ToString();



                }

                me.Close();
            }




}

I am still getting an error "No parameters given for one or more values" I am sure that the code is right.

You'll need to add a parameter to your SQL query. For example:

string myName = myComboBox.SelectedItem.Text;
string Query = "SELECT * FROM [Database] WHERE Name = ?";
OleDbConnection conn = new OleDbConnection(connection);
OleDbCommand cmd = new OleDbCommand(Query, conn);

cmd.Parameters.Add(new OleDbParameter("@name", myName));

conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();

while(reader.Read())
etc...

I'm not sure of the exact syntax for the OLE DB .NET Provider, but hopefully this helps somewhat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM