简体   繁体   中英

Retrieving data in DataGridView using SELECT on MySQL

I have a Windows Forms Application. I have to search data from the MySQL database using the "Like" operator. I have used the placeholder (@test, see code below) for the search term but it does not happen.

In simple, I have a TestBox named txtSearch in which I can enter the name of a student partially or completely. I need to retrieve all the entries matching search criteria on DataGrid.

Please check my code below and let me know where I am wrong (Conn String is removed below) :

try
{
dataGridView1.Visible = true;
BindingSource bs = new BindingSource();
DataTable newadm = new DataTable();
String term = txtSearch.Text;
string db = ----Connection String goes here----

bs.DataSource = newadm;
this.dataGridView1.DataSource = bs;

MySqlConnection conn = new MySqlConnection(db);
conn.Open();

string s = "select * from newadm where firstname like '%@term%' OR lastname like '%@term%'";
MySqlCommand cmd = new MySqlCommand(s, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@term", MySqlDbType.VarChar).Value = txtSearch.Text;

MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = new MySqlCommand(s, conn);

da.Fill(newadm);
da.Update(newadm);
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}

I get no results in DataGrid using this code(and many variations of it). If I remove the "@Term" place holder, and replace the exact terms, it works.

Please help out. Thanks in advance.

Try,

string s = "select * from newadm where firstname like @term OR lastname like @term";
MySqlCommand cmd = new MySqlCommand(s, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@term", MySqlDbType.VarChar,40).Value = "%" + txtSearch.Text + "%";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM