C# MDI can't populate listbox on child form - c#

I am trying to populate a listbox in C# from a table in sql server. The table is set up as:
tblTables
TableID int
SeatingCapacity int
CurrentCapacity int
The code I am trying to use is:
private void fillListBox()
{
String connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter();
String commandString = "SELECT TableID, SeatingCapacity, CurrentCapacity from tblTables";
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
conn.Open();
cmd.CommandText = commandString;
cmd.Connection = conn;
dr = cmd.ExecuteReader();
lstTableList.Items.Clear();
lstTableList.BeginUpdate();
while (dr.Read())
{
lstTableList.Items.Add(dr.GetInt32(0) + " - " + dr.GetInt32(1) + " - " + dr.GetInt32(2));
}
lstTableList.EndUpdate();
dr.Close();
conn.Close();
}
And the code for the parent form to transfer is:
private void mnuFormsTables_Click(object sender, EventArgs e)
{
frmTables aTables = new frmTables();
aTables.MdiParent = this;
aTables.Show();
aTables.Focus();
}
I call fillListBox() is the form load of frmTables. However when I put a break point on
String connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
It shows that right after that line the code jumps to the parent form at
aTables.Show();
Any help would be greatly appreciated. I am also not sure if that is the proper way to populate the listbox either. Preferably it would be nice if the listbox could show the table ID and add "Full" beside it if the current capacity >= seating capacity.
The github repo URL for this is https://github.com/resistince/StaufferRestaurant
EDIT: If I use:
String connectionString = Properties.Settings.Default.StaufferRestaurantConnectionString;
instead of using the ConfigurationManager it works. I have System.Configuration.dll as a reference and the proper using statement so I don't know why it doesn't work right.

Related

Show a data from database to a label

I'm new to c# programming and have a problem retrieving data from database to a label text. Here is the code what I was trying to do.
private void label3_Click_1(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("Server=localhost; Database=car_rental; user=root; Pwd=; SslMode=none");
DataTable dTable = new DataTable();
con.Open();
MySqlDataReader dr = null;
MySqlCommand cmd = new MySqlCommand("Select * from login where username=" + username, con);
dr =cmd.ExecuteReader();
while (dr.Read())
{
label3.Text = (dr["username"].ToString());
}
con.Close();
}
The problem in your code is created by the concatenation of a string (username) to another string (the sql query). This is a well known source of problems, going from syntax errors (the engine is not able to parse correctly the query text) to a much worse problem known as Sql Injection.
The well known solution is to use parameters instead of concatenated strings
private void label3_Click_1(object sender, EventArgs e)
{
using(MySqlConnection con = new MySqlConnection("Server=localhost; Database=car_rental; user=root; Pwd=; SslMode=none"))
{
con.Open();
// A single string with a parameter placeholder
string sqlCmd = "Select * from login where username=#name";
using(MySqlCommand cmd = new MySqlCommand(sqlCmd, con))
{
// Associate a value to the required parameter
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = username;
using(MySqlDataReader dr =cmd.ExecuteReader())
{
// Supposing you have just one user with that name
if(dr.Read())
{
label3.Text = dr["username"].ToString();
}
else
{
label3.Text = "User not found!";
}
}
}
}
Notice how I have added the using statement around each disposable object required to query the database. This statement ensures that the objects involved are disposed at the end of their use freeing the valuable unmanaged resource kept during their usage.

When trying to retrieve data from the database I get an error "InvalidOperationException was unhandled"

I have a form named Form1:
There is one ComboBox and one TextBox, when I select US$ from the ComboBox then it must retrieve data from the database and display 150 in the TextBox.
This is myform code:
For ComboBox;
namespace PCJ_System
{
public partial class Form1 : Form
{
SqlConnection conn;
SqlCommand cmd;
SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string str = "server = DESKTOP-LKEG8FM\\SQLEXPRESS;initial catalog= PCJ_DB ; Integrated Security=True;";
SqlConnection conn = new SqlConnection(str);
conn.Open();
conn = new SqlConnection(str);
string GetData = "Select [FC_Rate] from Forcur where FC_TYPE ='" + comboBox1.Text + "' ";
cmd = new SqlCommand(GetData, conn);
var returnValue = cmd.ExecuteScalar();
textBox1.Text = returnValue.ToString();
conn.Close();
}
}
}
My database table Forcur:
ID |FC_TYPE |FC_RATE|
1 US$ 150
2 UK# 210
What's wrong with my code?
This might not be the exact answer you are looking for, but you need to take care of following:
1) Assign DB connection string to SqlConnection object and open connection.
2) Since you are assigning one value to textbox, you need to use ExecuteScalar instead of ExecuteReader
Once you fix this, you should get the desired result.
Example:
conn=new SqlConnection(connectionStringHere);
conn.Open();
string GetData = "Select [FC_Rate] from Forcur where FC_TYPE ='" + comboBox1.Text + "' ";
cmd = new SqlCommand(GetData, conn);
var returnValue = cmd.ExecuteScalar();
textBox1.Text = returnValue.ToString();
conn.close();
Note: You still have SQL injection attack open in your SQL query. Try using varables instead to stop that.

C# cant get data from database table in combobox

when i load my application i need to fill the combobox cbkeuze with the row loginnaam from table gebruik
The error I am getting is: Can't change the items because property Data Source is set.
Here is my code:
private void Form1_Load(object sender, EventArgs e)
{
// SQL Connectie opzetten
SqlConnection Conn = new SqlConnection();
Conn.ConnectionString = #"Integrated Security=true;Initial Catalog=Wachtwoord;Data Source=LAPTOP-PDI9B3LP\SCHOOL";
Conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
// Alles selecteren van tabel Favorieten
cmd.CommandText = "select * from gebruik";
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
// Tabel wegschrijven in Applicatie
string loginnaam = dr.GetString(0);
cbKeuze.Items.Add(loginnaam);
}
dr.Close();
// Database connectie sluiten
Conn.Close();
}
You should check your combobox properties and see if DataSource is initiated
You can add loginnaam's to List loginnaams until while loop ends. After dr.Close() line, use cbKeuze.DataSource = loginnaams.
This will work for you.

Display number of records in a table

I'm trying to display numbers of records (in table) using C# Windows form . Bud It display "1" as output for every time . Here is the code.
private void button1_Click(object sender, EventArgs e)
{
string constr = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Visual Studio/database.mdf;Integrated Security=True";
SqlConnection con = new SqlConnection(constr);
con.Open();
string query= "select Count(*) from Student where Name like '%b%' ";
SqlCommand cmd = new SqlCommand(query1, con);
SqlDataReader dr = cmd.ExecuteReader();
int count = 1;
while (dr.Read())
{count++;}
label1.Text ="Following records : "+count+" ";
}
selecting count(*) returns one record with the value of the column holding the number of rows in the table. You don't need to count the number of rows in the result, you just need to get it from the first (and only) row:
int count = 0;
if (dr.Read()) {
count = dr.GetInt32(0);
} else {
// something went horribly wrong. Throw an exception perhaps?
}
If you need to count all of your records, then you need to remove LIKE filter from the query.
You do not have to use SqlDataReader - the ExecuteScalar is enough.
For the start, your code should be:
private void button1_Click(object sender, EventArgs e)
{
string constr = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Visual Studio/database.mdf;Integrated Security=True";
SqlConnection con = new SqlConnection(constr);
con.Open();
string query= "select Count(*) from Student";
SqlCommand cmd = new SqlCommand(query1, con);
int count = (int)cmd.ExecuteScalar();
label1.Text ="Following records : "+count+" ";
}
Also, consider learning about using statement which enforces good practice for releasing and disposing resources.
Very important thing when you work with the database connections, transactions and commands.
SqlCommand with using statement
i think you should use rownum function it will display the number for each record for more info check this link http://docs.oracle.com/cd/B12037_01/server.101/b10759/pseudocolumns008.htm

How Do I Populate Text Boxes With Sql Database Data Using One Combo Box

Hey everyone pretty new to SQL Database functions but have been coding in c# for about a year now still not that great at it but I'm getting there!
I'm currently creating a football application and to Edit players and Matches i was wanting to use one drop down combo box to retrieve data from an SQL database which then would populate other text boxes and combo boxes. I've had a go at it myself but don't know where i'm going wrong.
On form load my connection opens i populate my datasets and i execute this method to populate my combobox
private void Navigate()
{
string showPlayers = "SELECT * From Add_Players";
SqlCommand cmdData = new SqlCommand(showPlayers, conn);
SqlDataReader myReader = cmdData.ExecuteReader();
while (myReader.Read())
{
comboEditPlayer.Items.Add(myReader[0]);
}
conn.Close();
}
After which in the combo box selected index changed method i have this code
private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
string showPlayers = "SELECT * From Add_Players WHERE Player_ID ='"
+ comboEditPlayer + "' ;";
SqlCommand cmdData = new SqlCommand(showPlayers, conn);
SqlDataReader myReader = cmdData.ExecuteReader();
while (myReader.Read())
{
comboEditPlayerPos.Items.Add(myReader[1]);
txtEditPlayerName.Text = myReader[2].ToString();
txtEditPlayerSecond.Text = myReader[3].ToString();
comboEditPlayerStatus.Items.Add(myReader[4]);
}
conn.Close();
conn.Dispose();
}
catch (Exception comboFail)
{
MessageBox.Show(comboFail.ToString());
}
}
I've been told this code is open and i need to use parameterized queries for preventing hacker attempts which i have started but do not know what Parameter i should be adding to the code i have for this is below
private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString =
ZimbFootball.Properties.Settings.Default.Football2ConnectionString;
using (SqlConnection connection = new SqlConnection (connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(
"SELECT * From Add_Players WHERE Player_ID ="
+ comboEditPlayer.SelectedValue + "", connection))
{
command.Parameters.Add(new SqlParameter ("",));
}
}
}
All help is appreciated and please go easy on me :P
You could add a parameter to the collection with the value of your ComboBox, then execute the query and read back the values from the reader
private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString =
ZimbFootball.Properties.Settings.Default.Football2ConnectionString;
using (SqlConnection connection = new SqlConnection (connectionString))
using (SqlCommand command = new SqlCommand(
"SELECT * From Add_Players WHERE Player_ID =#id", connection))
{
connection.Open();
command.Parameters.AddWithValue("#id", comboEditPlayer.Text);
using(SqlDataReader myReader = command.ExecuteReader())
{
while (myReader.Read())
{
comboEditPlayerPos.Items.Add(myReader[1]);
txtEditPlayerName.Text = myReader[2].ToString();
txtEditPlayerSecond.Text = myReader[3].ToString();
comboEditPlayerStatus.Items.Add(myReader[4]);
}
}
}
}

Categories

Resources