Can't select numerical values from database into a TextBox

54 Views Asked by At

I want to use a combobox to retrieve data from an access database, but it doesn't work with numerical values.

This part of the code is the connection string and object:

public partial class StockControl : Form
{
    OleDbConnection connection = new OleDbConnection();
    public StockControl()
    {
        InitializeComponent();
        connection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Folder\NewStockControl.mdb;Persist Security Info=False;";
    }

Here is the code I used to retrieve the field ProductName in the Access database (StockControl is the name of the form I created):

private void StockControl_Load(object sender, EventArgs e)
    {
        try
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            string query = "select ProductName from Products";
            command.CommandText = query;

            OleDbDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                cbProductId.Items.Add(reader["ProductName"].ToString());
            }
            connection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error" + ex);
        }

    }

And here is the code I added to the combo box (cbProductId)

private void cbProductId_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.CommandType = CommandType.Text;
            command.Connection = connection;
            string query = "SELECT * from Products WHERE ProductName='"+cbProductId.Text+"'";
            command.CommandText = query;
            OleDbDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                txtStockName.Text = reader["ProductName"].ToString();
                txtStockQty.Text= reader["SupplyLeft"].ToString();
            }
            connection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error" + ex);
        }
    }

There are two textboxes in the StockControl form: txtStockName and txtStockQty, and I want the fields ProductName and SupplyLeft to be displayed in those textboxes respectively. However whenever I run the code the only value that shows is ProductName, but SupplyLeft doesn't. I assume it has to do with the fact that it is an integer rather than a string, but I don't know how to convert the text box to be able to display the value SupplyLeft.

0

There are 0 best solutions below