I will use ADO.net to connect to a database, and i will use an oracle database.
My database will consist of 1 table, employee, which have the following attributes:
- ID_employee (char 5)
- employee_name (varchar2 40)
Then, drag a listbox (for the list of ID_employee) and a textbox(for displaying the name of the selected ID), don't forget to name them. I will name my listbox "listID" and the textbox "txtName".
Now add an event (Loaded event) in the window tag in your XAML
then open Window1.xaml.cs, there will be a new function named Window_Loaded, this function will be called when the window is loaded.
In this function we will create a new connection. Before we do that, add
"using System.Data.Common" and "using System.Data".
Then make 2 global variable :
DbProviderFactory factory;
DbConnection connection;
Now in the Window_Loaded function add this
factory = DbProviderFactories.GetFactory("System.Data.OracleClient"); connection = factory.CreateConnection(); connection.ConnectionString = "Data Source=localhost;Persist Security Info=True;User ID=erkape27;Password=erkape;Unicode=True"; connection.Open();
this will create a new connection to an localhost Oracle database, with user = erkape27 and password = erkape. Just change the user and password with your user and password.
then lets make a simple query to display all item from the employee table.
DbCommand command = factory.CreateCommand(); //create a new command command.CommandText = "Select * from EMPLOYEE"; //make the query command.Connection = connection; //connect the command
then we will change the list source item with the query result
DbDataAdapter adapter = factory.CreateDataAdapter();//create new adapter
adapter.SelectCommand = com;
DataTable dt = new DataTable(); //create a new table
DataSet ds = new DataSet();
adapter.Fill(ds, "EMPLOYEE");
dt = ds.Tables[0]; //copy the table from the dataset to the dataTable
listBox.ItemsSource = dt.DefaultView; //change the source of the list with the
dataTable listBox.DisplayMemberPath = "ID_employee"; //display ID_employee in the
list connection.Close() //dont forget to close the connection
Now run your program, the list should display the list of ID from your database.
Now, we will do the data binding with the txtName and the listID.
open the XAML file.
then change the textbox like this
Path=SelectedItem.EMPLOYEE_NAME}"/>
run your program, and try to select a different item in the list, the text in the textbox should change..
that's all, if you wanna display other information in the textbox, just change the data binding path with other column nama, like maybe path=SelectedItem.ADDRESS.
hope it helps you people.