Filtering listbox with textbox - c#

I know this question might of been asked a couple of times but I looked around and I couldn't find the right thing that would work for me.
So, here's my question.
I currently have a listbox that takes the column "name" out of a mysql database.
As soon as the application starts up it loads all the names in the listbox.
But because there could be alot of names I would like a filter option.
So, if you have for example Mark Jones, Billy Peter in the listbox and you would type Mark in the textbox only Mark Jones would show up.
Fill list box initialize component:
void fill_listbox()
{
string constring = "datasource=localhost;port=3306;username=root;password=xdmemes123";
string Query = "select * from life.players ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString("name");
namelistbox.Items.Add(sName);
}
}catch (Exception ex)
{
MessageBox.Show("Something went wrong. Error copied to clipboard.");
Clipboard.SetText(ex.Message);
}
}
The textbox is called "SrchBox" and the listbox "namelistbox"
I've tried a couple of things but it never seemed to work.
Thanks.

Instead of assigning the names from the SQL query directly to the listbox, assign them to a list or an array that you can then filter on later:
List<string> playerNames;
void fill_listbox()
{
string constring = "datasource=localhost;port=3306;username=root;password=xdmemes123";
string Query = "select * from life.players ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString("name");
playerNames.Add(sName);
}
foreach(string name in playerNames)
{
namelistbox.Items.Add(name);
}
}catch (Exception ex)
{
MessageBox.Show("Something went wrong. Error copied to clipboard.");
Clipboard.SetText(ex.Message);
}
}
You can then add an event handler for the TextBox's TextChanged event:
void textBox_TextChanged(object sender, EventArgs e)
{
// create filtered list from playerNames
var filteredList = from name in playerNames
where CultureInfo.CurrentCulture.CompareInfo.IndexOf(name, textBox.Text, CompareOptions.IgnoreCase) >= 0
select name;
namelistbox.Items.Clear();
foreach (string name in filteredList)
namelistbox.Items.Add(name);
}

Related

user selection Combobox then to Labels according to database MS Access c#

i have the following code below and what im trying to do is on the comboBox there is "ID" from my database and this ID represents every survey detail that Admin used to create so when the user goes to view the survey they click on the survey number in comboBox and the labels will change according to the database. I tried it with the below code but unfortunatley all it seems to do is grab a random one, if someone could help that would be amazing. It doesnt have to be like below, just as long as it works,
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con.Open();
string query = "SELECT * FROM tbl_newsurvey ";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = query;
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string name = reader["txtname"].ToString();
lblname.Text = name;
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
You can try this to search data from database using Combobox
I use parameterized query to avoid SQL Injection
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con.Open();
string query = "SELECT * FROM tbl_newsurvey WHERE [ColumnName] = #ComboBoxValue";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#ComboBoxValue", comboBox1.SelectedIndex.ToString())
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read() == true)
{
string name = reader["txtname"].ToString();
lblname.Text = name;
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}

Show information from MySQL database

I want to pass the information I get from a database to a label. How can I pass the information into a variable.
How can I do this?
private void button1_Click(object sender, EventArgs e)
{
var numero = textBox1.Text;
string connection_string = "datasource=xxx;port=111;username=xxx;password=xxx";
string Query = "select * from xxx.lojass where nome =" + numero;
MySqlConnection conDate = new MySqlConnection(connection_string);
MySqlCommand cmdDate = new MySqlCommand(Query, conDate);
MySqlDataReader myReader;
try
{
conDate.Open();
myReader = cmdDate.ExecuteReader();
MessageBox.Show("Conected");
while (myReader.Read())
{
label1.Text
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Proper coding. Explanation in code comments below
private void button1_Click(object sender, EventArgs e)
{
try
{
const connStr = "datasource=xxx;port=111;username=xxx;password=xxx"; // constant
// Instead of "select *" select particular column(s), it will help with reader columns later
var sql = "select column1 from xxx.lojass where nome = #1"; // you need to parameterize. Never push text box value directly into sql
// important to use "using" to release resources
using (var conn = new MySqlConnection(connStr))
{
using (var cmd = new MySqlCommand(sql, conn))
{
// assuming "nome" is string. If the value is other datatype - convert it
// Better yet - create parameter where you explicitly specify mySql data type
cmd.Parameters.AddWithValue("#1", textBox1.Text);
conn.Open();
using (var reader = cmd.ExecuteReader()) // Since single value expected another way doing it - ExecuteScalar
{
// you only fill one single value, so makes sense to use IF, not WHILE
if (reader.Read())
label1.Text = reader["column1"].ToString();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Database values in textbox if select Combobox

I am trying to write code for a form that writes to a sql table. I use data form other tables to complete the form (along with user input). I have a checkbox that options the source of a combobox (ddDefect) - it is based on one of two sql LIKE queries - so, the combox will display the results of one LIKE query if the checkbox = true and the other LIKE query if it = false. This part works great. Problem is; I cannot seem to figure out how to take the selected item in the combobox and display text form another column in my textbox (txtNcm)
I have tried various ways and this seems to make the most sense to me (though I am only a beginner and clueless) but I get nothing in my text box.
here is the code that I have been trying:
private void ddDefect_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = "Data Source=TS-ERP01;Initial Catalog=Touchstn02;Integrated Security=True";
string Query = "select * from Defect_Codes Where DESCP_91= ' " + ddDefect.Text + " ';";
SqlConnection conDataBase = new SqlConnection(constring);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sDEF = myReader["DEFECT_91"] as String;
txtNcm.Text = sDEF;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Your sql command text contains spaces before and after the value of ddDefect.
....DESCP_91= ' " + ddDefect.Text + " ';";
^ ^
These spaces will be passed as is to the database engine and, unless you have a very specific datatype in the database column (CHAR/NCHAR) with these exact spaces around the values in the column, the command will never find any data.
But this is not the end of your problems. Concatenating strings in this way is a well known source of problems. What if the ddDefect.Text contains a single quote? Another syntax error. Then there is the problem of Sql Injection vulnerability, a very serious security problem.
So you should use a parameterized query like this
string constring = "Data Source=TS-ERP01;Initial Catalog=Touchstn02;Integrated Security=True";
string Query = "select * from Defect_Codes Where DESCP_91= #ds91";
using(SqlConnection conDataBase = new SqlConnection(constring))
using(SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase))
{
try
{
conDataBase.Open();
cmdDataBase.Parameters.Add("#ds91", SqlDbType.NVarChar).Value = ddDefect.Text;
using(SqlDataReader myReader = cmdDataBase.ExecuteReader())
{
while (myReader.Read())
{
string sDEF = myReader["DEFECT_91"].ToString();
txtNcm.Text = sDEF;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Notice also that SqlConnection, SqlCommand and SqlDataReader are disposable objects and thus you should try to always use the using statement to be certain that these objects free the unmanaged resources acquired during they work (particularly the SqlConnection object)

how to refresh the combo box in c#? this the codes

string query = "SELECT * FROM inv.product;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
while (myReader.Read())
{
string sprodID = myReader.GetString("productID");
cmbdel.Items.Add(sprodID);
}
}
Create a function of you existing code like this,
private void BindCombo()
{
cmbdel.Items.Clear(); // Clear the combobox items here
// And bind again...
string query = "SELECT * FROM inv.product;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
while (myReader.Read())
{
string sprodID = myReader.GetString("productID");
cmbdel.Items.Add(sprodID);
}
}
}
Now you can call this method everytime when you delete the item.
Hope it works, thanks.
You can do either of the following to remove an item from the combo box.
cmbdel.Items.RemoveAt(index);
cmbdel.Items.Remove(Value);
Before assigning new set of values,make sure that you call cmbdel.Items.Clear(). It will clear all the items from the combo box.

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