Can't select numerical values from database into a TextBox - c#

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.

Related

Output Not Displaying in TextBox in C#

I am new to C# and I have connected it with Oracle11g and using Visual Studio 2013 as a tool. I am trying to display a 'name ' that is being returned by a query to a textbox but it is neither displaying an Error Message nor displaying the Output. Pleases help me to resolve this problem. Thanks... here is my code..
private void button1_Click(object sender, EventArgs e)
{
try
{
string oradb = "Data Source=ORCL;User Id=hr; Password=123;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select name from std where cgpa=2.82;";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
textBox1.Text = dr.GetString(0);
conn.Dispose();
}
catch (Exception ex) { MessageBox.Show("\n"+ex); }
}
after setting textBox1.Text = dr.GetString(0);
it is giving me the attached exception.
Array indexes start at index zero, not 1. The returned string (if any) is at
textBox1.Text = dr.GetString(0);
A more correct way to write your code is the following
private void button1_Click(object sender, EventArgs e)
{
try
{
string oradb = "Data Source=ORCL;User Id=hr; Password=123;";
// Use the using statements around disposable objects....
using(OracleConnection conn = new OracleConnection(oradb))
using(OracleCommand cmd = new OracleCommand())
{
conn.Open();
// These two parameters could be passed directly in the
// OracleCommand constructor....
cmd.Connection = conn;
cmd.CommandText = "select name from std where cgpa=2.82;";
// Again using statement around disposable objects
using(OracleDataReader dr = cmd.ExecuteReader())
{
// Check if you have a record or not
if(dr.Read())
textBox1.Text = dr.GetString(0);
}
}
}
catch (Exception ex) { MessageBox.Show("\n"+ex); }
}
And if your code is supposed to return just a single record with a single column then you can use the more performant ExecuteScalar without building an OracleDataReader
// Again using statement around disposable objects
object result = cmd.ExecuteScalar();
if(result != null)
textBox1.Text = result.ToString();

button click to search multiple Access tables

I have a simple feature to search an Access table for a given serial number by button click.
Is there a way to add to what I have below to search multiple tables for the serial number and display in datagridview?
private void searchItembtn_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(serialSearch.Text))
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.Parameters.Add("#searchSerial", OleDbType.VarWChar).Value = serialSearch.Text;
string searchFB = "SELECT * FROM Inventory WHERE SerialNumber = #searchSerial";
command.CommandText = searchFB;
connection.Close();
OleDbDataAdapter db = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
db.Fill(dt);
dataGridFB.DataSource = dt;
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
searchHide();
connection.Close();
}
}

Call form load event in another function

I need advice on how to call the form load at other areas in my code to avoid excess copy and paste. I basically need to load the page at other areas after pressing buttons in an interface. I need all of the code that exists and as you can see it is quite a bit to copy and paste multiple times.
public void FBinterface_Load(object sender, EventArgs e)
{
txtSerial.Focus();
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string SerialQuery = "select SerialNumber from Inventory";
command.CommandText = SerialQuery;
//TO READ DATA
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
comboSerial.Items.Add(reader["SerialNumber"]);
}
connection.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string PartQuery = "select PartNumber from Inventory";
command.CommandText = PartQuery;
//TO READ DATA
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
comboPart.Items.Add(reader["PartNumber"]);
}
connection.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string ROnumberQuery = "select ROnumber from Inventory";
command.CommandText = ROnumberQuery;
//TO READ DATA
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
comboRO.Items.Add(reader["ROnumber"]);
}
connection.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string LocationQuery = "select Location from Inventory";
command.CommandText = LocationQuery;
//TO READ DATA
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
comboLocation.Items.Add(reader["Location"]);
}
connection.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
}
Move your logic to another method and call it when you want
public void FBinterface_Load(object sender, EventArgs e)
{
MyLogic();
}
private void MyLogic()
{
txtSerial.Focus();
try
{
//removed for brevity
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
}
now call MyLogic method when you want.
For example:
public void button1_Click(object sender, EventArgs e)
{
//some code
MyLogic(); //calling the whole logic you want.
//extra code
}
Did you try:
FBinterface_Load(this,null);

Bind two pages in wpf

I need to populate a combobox in page1 with the address details of a selected name contained in another combobox held in the MainWindow page. I have tried the code below, but combobox name in MainWindow is not recognised.
MainWindow:
private void displayParts()
{
try
{
sc.Open();
string Query = "select * from Parts";
SqlCommand createCommand = new SqlCommand(Query, sc);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
string Name = dr.GetString(1);
cbParts.Items.Add(Name);//Displaying a list in the Combo Box
}
sc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Page1:
private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
string constring = "Data Source=.;Initial Catalog=**.MDF;Integrated Security=True";
DataContext=MainWindow.
string Query = "select * from Partners where Name='" + cbParts.SelectedItem.ToString() + "' ;";
SqlConnection conDataBase = new SqlConnection(constring);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
sc.Open();
myReader = cmdDataBase.ExecuteReader();
if (myReader.Read())
{
txtPartner.Text = myReader["Name"].ToString();
}
myReader.Close();
sc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
// may need to cast this to your MainWindow's type
var mainWindow = Application.Current.MainWindow;
//...
mainWindow.cbParts.Items.Add(Name);
Additionally, you could bind your combobox to an ObservableCollection property, and add the items to the collection.

How to bind field to a text box

I need to bind a field(ComputerTag) to a Text field.
This my code:
public void load()
{
//Intializing sql statement
string sqlStatement = "SELECT Computertag FROM Computer WHER
ComputerID=#ComputerID";
SqlCommand comm = new SqlCommand();
comm.CommandText = sqlStatement;
int computerID = int.Parse(Request.QueryString["ComputerID"]);
//get database connection from Ideal_dataAccess class
SqlConnection connection = Ideal_DataAccess.getConnection();
comm.Connection = connection;
comm.Parameters.AddWithValue("#ComputerID", computerID);
try
{
connection.Open();
comm.ExecuteNonQuery();
//Bind the computer tag value to the txtBxCompTag Text box
txtBxCompTag.Text= string.Format("<%# Bind(\"{0}\") %>", "Computertag");
}
catch (Exception ex)
{
Utilities.LogError(ex);
throw ex;
}
finally
{
connection.Close();
}
}
but "txtBxCompTag.Text = string.Format("<%# Bind(\"{0}\") %>", "Computertag");" this line of code doesn't bind the value to the text box. How can I assign the value to the text box?
You can use ExecuteReader
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
}
}
Above code comes from msdn: http://msdn.microsoft.com/en-us/library/9kcbe65k(v=vs.90).aspx
The function ExecuteNonQuery is used for insertion/updation. Use SqlDataReader

Categories