I have a problem with this code. Every time I type a text in the TextBox
this happen. there's an added column and its empty(I want to remove this)
public void searchData()
{
string sql = "Select * from Inventory";
cmd = new OleDbCommand(sql, con);
try
{
con.Open();
cmd.Connection.CreateCommand();
string value = cboFields.Text;
switch (value)
{
case "ID":
cmd.CommandText = "Select * from Inventory where ID LIKE @searchKey";
break;
case "Quantity":
cmd.CommandText = "Select * from Inventory where Quantity LIKE @searchKey";
break;
case "Unit":
cmd.CommandText = "Select * from Inventory where Unit LIKE @searchKey";
break;
case "ItemCode":
cmd.CommandText = "Select * from Inventory where ItemCode LIKE @searchKey";
break;
case "ItemName":
cmd.CommandText = "Select * from Inventory where ItemName LIKE @searchKey";
break;
case "Cbm":
cmd.CommandText = "Select * from Inventory where Cbm LIKE @searchKey";
break;
case "TotalCbm":
cmd.CommandText = "Select * from Inventory where TotalCbm LIKE @searchKey";
break;
case "":
cmd.CommandText = "Select * from Inventory";
MessageBox.Show("Select fields where you want to searchData for");
txtSearch.SelectionStart = 0;
txtSearch.SelectionLength = txtSearch.Text.Length;
break;
}
cmd.Parameters.AddWithValue("@searchKey", "%" + txtSearch.Text.ToString() + "%");
OleDbDataAdapter adap = new OleDbDataAdapter(cmd);
adap.Fill(dt);
DGVinventory.DataSource = dt;
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
First, why not use formatting instead of combersome
switch
? Next, do not use*
in the query, just enumerate all the columns you really want: