SQL query based on combobox selection - c#

I am creating a database application and I'm having difficulty implementing a query. I have a query which populates a combobox with customer's bank accounts this is the code for the query:
private void ShowAccounts()
{
string sql = "SELECT account.custid, product.name FROM account INNER JOIN product ON account.prodid = product.prodid WHERE account.custid = #AccountID";
using (OleDbConnection connection = new OleDbConnection(Properties.Settings.Default.ConnectionScring))
{
OleDbCommand command = new OleDbCommand(sql, connection);
command.Parameters.AddWithValue("#AccountID", customerData.CustomerID);
connection.Open();
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
comboAccounts.Items.Add(reader["name"].ToString());
}
}
}
This works the way I need it to but based on the account selection I need to display the account balance and I'm wondering how to go about writing that query. Any help would be appreciated.
Thank you

I guess this is what you are trying to do? I am guessing on your column and table names so you will need to modify the sql statement if I got it wrong.
private string Get_Balance(string AccountNumber)
{
string sql = "SELECT balance FROM account WHERE custid = #AccountID";
string balance = "";
using (OleDbConnection connection = new OleDbConnection(Properties.Settings.Default.ConnectionScring))
{
OleDbCommand command = new OleDbCommand(sql, connection);
command.Parameters.AddWithValue("#AccountID", AccountNumber);
connection.Open();
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
balance = reader["balance"].ToString();
}
}
}
return (balance);
}
Use the SelectedIndexChanged event of your combo box to call the above code. You will need to add the event handler to the combo box (just double click it on the form and VS will do it for you).
private void comboAccounts_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboAccounts.Text != "")
{
balanceLabel.text = Get_Balance(comboAccounts.text); //Or whatever you named the label you want your balance to to into.
}
}
After you populate your combo box with your code, whenever the combo box is dropped down and changed it will pass the text of whatever is in the combo box to Get_Balance which will return a string that will be placed in the label.

Related

How to get a list box to display its results based on previous combo box.

I am trying to populate a combo box from SQL where when I select an Item from the first box the options get limited in the 2nd box. The fist box has a selected index change event, but I can't seem to figure out how to limit the results.
Here is what I have:
private void cb_college_SelectedIndexChanged(object sender, EventArgs e)
{
lb_allMajors.Items.Clear();
lb_allMajors.Items.Add(cb_college.SelectedIndex);
}
private void populateMajors()
{
try
{
string SQL;
SQL = "SELECT DISTINCT major_name FROM majors";
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(SQL, conn);
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
lb_allMajors.Items.Add(reader.GetString(0));
}
}
}
catch (SqlException err)
{
MessageBox.Show(err.Message);
}
}
Each major in the majors table in the database has a college ID column that links to the colleges table. So when you select a college (e.g. Business) I want the major box to only show majors in the college of business.
I'm not 100% on exactly what you're after or what the example is showing, but I think you just need to supply your populateMajors() method with a parameter containing the college ID, or the SelectedIndex, whichever you want to use.
For example:
private void cb_college_SelectedIndexChanged(object sender, EventArgs e)
{
populateMajors(cb_college.SelectedIndex); // OR More likely Get College ID from Combobox
}
private void populateMajors(int CollegeId)
{
try
{
string SQL;
SQL = "SELECT DISTINCT major_name FROM majors WHERE <yourcollegeindexcol> = " + CollegeId;
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(SQL, conn);
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
lb_allMajors.Items.Add(reader.GetString(0));
}
}
}
catch (SqlException err)
{
MessageBox.Show(err.Message);
}
}
I doubt that SelectedIndex is the right parameter to send, but you get the picture.
You might find it better to use the ComboBox.DataSource property too rather than Items.Add - search for ComboBox.DataSource online to see it's usage.

Combo Box on dropdown method only called once

I am using two combo boxes in one of my programs. The first combo box contains the products while the second contains the categories. I have a method which loads he categories on the second combo box from the database when ever a new item is selected on the first combo box "products". The first time i run the program and select an item it loads from the database but if i try it again nothing loads. Please help with what might be causing this.
private void load_schemes(object sender, EventArgs e)
{
DataTable subjects = new DataTable();
DBConnect con = new DBConnect();
using (SqlConnection CONN = con.getConnection())
{
try
{
schemename.Items.Clear();
SqlDataAdapter adapter = new SqlDataAdapter();
String schemeType = schemetype.Text;
firstname.Text = schemetype.Text;
String SQL = "";
if (schemeType == "Family Scheme")
{
SQL = "select schemeID,SCHEMENAME from registration.familyMedicalScheme";
}
else if (schemeType == "Insurance Scheme")
{
SQL = "select schemeID,SCHEMENAME from registration.insurancescheme";
}
else if (schemeType == "Company Scheme")
{
SQL = "select schemeID,SCHEMENAME from registration.companymedicalscheme";
}
adapter.SelectCommand = new SqlCommand(
SQL, CONN);
adapter.Fill(subjects);
schemename.DataSource = subjects;
schemename.DisplayMember = "SCHEMENAME";
//schemename.ValueMember = subjects.;
}
catch (Exception ex)
{
// Handle the error
}
finally
{
CONN.Close();
}
}
}
I changed the solution and used Items.Add instead of data binding method and it is now working
adapter.Fill(subjects);
foreach (DataRow da in subjects.Rows)
{
schemename.Items.Add(da[0].ToString());
}

Display a list of item to CheckListBox when comboBox item is selected

I have a windows form application. Inside the form, I have a ComboBox and a list box. When I select the comboBox, I want to display a list of item that the user can check in the checkListBox, I figured out how to bind data to comboBox part but I am not sure how to display a list of values so that the user can select in the checkListBox. Let say I have a list of items that stored in a SQL database call item_table, how can I display it to the checkListBox according to when I select from the comboBox? Code for reference will be appreciated. Thanks
For example,
let say the user select "Amy" from the comboBox, the checkListBox will display a list of item "item 1, item2, item3, item4".
when the user select "Brad" from the comboBox, it will display a list of item: "item2, item5, item10
etc
Here is my database table in (SQL) server
user_Detail
In my user_Detail table , I have 10 user and each of them have a primary key (userId) and a column (userName);
item_Detail
In my item_Detail table, I have 20 items and they also have a primary key (itemId) and a column (itemName)
In the sql console, I inner join the two table (which I am not sure if I need to do the same in my SqlCommand in the code )
Here is my sql command in the console.
select
user_Detail.userId,
user_Detail.userName,
item_Detail.itemId,
item_Detail.itemName
from
item_Detail
INNER JOIN user_Detail ON user_Detail.userId = item_Detail.itemId
Here is my code
namespace Test {
public partial class MainForm: Form {
SqlConnection myConn;
SqlCommand myCommand;
SqlDataReader myReader;
SqlDataAdapter myDa;
DataTable dt;
DataSet ds = new DataSet();
public MainForm() {
InitializeComponent();
// loadComboBox
loadComboBox();
}
//Connect to my db to fetch the data when the application load
private void loadComboBox() {
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
string query = "Select * from user_Detail";
myCommand = new SqlCommand(query, myConn);
try {
myConn.Open();
myReader = myCommand.ExecuteReader();
string s = "<------------- Select an item ----------->";
itemComboBox.Items.Add(s);
itemComboBox.Text = s;
while (myReader.Read()) {
//declare a string
object userId = myReader[userId"];
object userName = myReader["userName"];
//my comboBox named userComboBox
userComboBox.Items.Add(userName.ToString());
}
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
//Display some items here (this is my checkListBox
private item_checkListBox(Object sender, EventArgs e){
}
private void load_item(){
}
I wish this could help you.
First, i just want to fix your loadComboBox() because reading it might lead to confusion.
private void loadComboBox() {
myConn = new SqlConnection("Server = localhost; Initial Catalog=dbName; Trusted_Connection = True");
string query = "Select * from user_Detail";
myCommand = new SqlCommand(query, myConn);
try {
myConn.Open();
myReader = myCommand.ExecuteReader();
string s = "<------------- Select an item ----------->";
itemComboBox.Items.Add(s);
itemComboBox.Text = s;
while (myReader.Read()) {
//declare a string
string userId = myReader["userId"].toString();
string userName = myReader["userName"].toString();
//my comboBox named userComboBox
userComboBox.Items.Add(userName);
}
myConn.Close();
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
Make sure to close sql connections after using it. Just open it again if youre going to use it.
Now, you added the userName of your users on your combobox.
Next lets create an event that will be fired whenever you choose from your combobox.
userComboBox.SelectedIndexChanged += (o,ev) => { ChangeCheckListItems(); };
The code above can be read as "if userComboBox changed selected index, call ChangeCheckListItems() method." Whenever you change selection, we will call the said method. You can put that code on your class constructor.
Now what does ChangeCheckListItems() method must contain.
private void ChangeCheckListItems(){
myCheckListBox.Items.Clear();
string selectedText = userComboBox.Text;
switch(selectedText){
case "Amy":
AddItemsForAmy();
break;
case "Brad":
AddItemsForBrad();
break:
}
}
So first, we make sure we clear the myCheckListBox before adding the items to avoid duplication since this method trigger every selection change.
Next we get the selected text from the userComboBox.
Then we will use a switch to choose what we will do depends on the selected userComboBox.
AddItemsForAmy() and AddItemsForBrad() are only example methods.
For example:
private void AddItemsForAmy(){
myConn = new SqlConnection("Server = localhost; Initial Catalog=dbName Trusted_Connection=true;"
string query = "Select * from item_Detail where itemId % 2 = 0"
myCommand = new SqlCommand(query, myConn);
try{
myConn.Open();
myReader = myCommand.ExecuteReader();
while(myReader.Read()){
string itemName = myReader["itemName"].toString();
myCheckListBox.Items.Add(itemName);
}
myConn.Close();
}
catch(SqlExcetion ex){
MessageBox.Show(ex.Message);
}
}
So in my example above, I selected all items with itemId that are even numbers.
And then on while() part, I added those items to the checklistbox.
Its your choice on what items are you going to display for Amy,Brad and other possible users on you database. You can also use parameterized method for shorter solution. Hope this helps. Sorry if its so long.

How to check if the primary key exists in my database from a textbox (windows form), c#

I have a textbox and a button in a windows form application.
I want to check if the primary key (persId) exists in my sql database/dataset (made with Visual studio) when I enter a number in the textbox and press the button. I dont know how to compare the text with persId from the database.
If the persId exists I want to fill two textboxes in a new form and show the persId and persName.
I am new to programming in C# so I have probably missed something. I looked at how to check if value exists in database from textbox c# but could not find an answer.
Thanks in advance!
public void searchPersId(string persId)
{
SqlConnection conn = new SqlConnection();
SqlCommand myCommand = new SqlCommand("SELECT persId FROM Customers WHERE persId = #persId", conn);
myCommand.Parameters.AddWithValue("#persId", persId);
if (textBox1.Text = myCommand ) //I dont know how to compare the values of textbox with myCommand..
{
//Show values (persId and persName) in two textBoxes in a new form.
}
else
{
MessageBox.Show("The ID does not exist.");
}
}
First, use the using-statement for everything implementing IDisposable like the connection to dispose unmanaged resources and to close the connection, even in case of an error.
Then you have to open the connection and to use ExecuteReader to get a datareader to check if there's at least one record with that ID, you can use reader.HasRows. You also have to select the persName if you want it as mentioned.
using(var conn = new SqlConnection())
using(var myCommand = new SqlCommand("SELECT persId, persName FROM Customers WHERE persId = #persId", conn))
{
myCommand.Parameters.AddWithValue("#persId", persId);
conn.Open();
using(var rd = myCommand.ExecuteReader())
{
bool personExists = rd.HasRows;
if(personExists)
{
// advance the reader to the first record, presuming there is only one, otherwise use a loop while(rd.Read)
rd.Read();
string persName = rd.GetString(1); // second field
// ...
}
else
{
MessageBox.Show("The ID does not exist.");
}
}
}
You can also use ExecuteScalar
public void searchPersId(string persId)
{
SqlConnection conn = new SqlConnection();
SqlCommand myCommand = new SqlCommand("SELECT persName FROM Customers WHERE persId = #persId", conn);
myCommand.Parameters.AddWithValue("#persId", persId);
object personName = myCommand.ExecuteScalar();
if(!string.IsNullOrEmpty(personName.ToString()))
//if (textBox1.Text = myCommand) //I dont know how to compare the values of textbox with myCommand..
{
//Show values (persId and persName) in two textBoxes in a new form.
textBox2.Text = personName.ToString();
}
else
{
MessageBox.Show("The ID does not exist.");
}
}
First you have to Execute the command.
SqlDataReader dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
// ... if it has rows then you know it match
}
else
{
// ... data doesn't exists
}
Then you can compare the result.

how to populate textbox with new Row ID in windows form

I'm creating a windows form and currently in the process of creating the "create member" form.
Now i wish to show to the user inputting data what the new members ID will be. So i thought of trying to show the new row ID within a text box. So if we take the example below, when the form loads, the new member ID should be shown in the textbox
I've tried to attempt it below but having difficulty getting the result from the sqlCommand. Or maybe im going the wrong way around doing it ha
Can anyone see how i can apply the id upon load?
private void frmAddMember_Load(object sender, EventArgs e)
{
using (var connection = new SqlConnection(Properties.Settings.Default.BioEngineeringDB))
{
connection.Open();
using (var cmd = new SqlCommand("SELECT * FROM Users WHERE UserID=(SELECT MAX(UserID) FROM Users", connection))
{
//cmd.Parameters.Add("#MYVALUE", SqlDbType.VarChar).Value = comboBox1.Text;
SqlDataReader re = cmd.ExecuteReader();
if (re.Read())
{
txtMemberId.Text = // result from the SQLCommand but i dont know how to get it
You can access current row cells by indexing DataReader with columns names, like this txtMemberId.Text = thisReader["UserID"]; //here you should do increment. But honestly, generating Id in select max(id) + 1 manner is odd, GUIDs nad Autoinc integer is more commonly used in our days.
Your MAX+1 should looks like:
private void frmAddMember_Load(object sender, EventArgs e)
{
using (var connection = new SqlConnection(Properties.Settings.Default.BioEngineeringDB))
{
connection.Open();
using (var cmd = new SqlCommand("SELECT (COALESCE(MAX(UserID), 0) + 1) as UserID FROM Users", connection))
{
SqlDataReader re = cmd.ExecuteReader();
if (re.Read())
{
txtMemberId.Text = re["UserID"].ToString();
remove your autoinc id column and add a guid id col instead. then you can generate the Id on the client with Guid.NewGuid().ToString()
Assuming your ID column is being generated by the database (auto increment, etc...) just get the ID when you create the record.
var cmd = new SqlCommand("INSERT INTO User(FirstName) VALUES('bob')");
var id = (int) cmd.ExecuteScalar();
txtMemberId.Text = id.ToString();

Categories

Resources