What’s wrong with my code? This code is from my VB .NET program which I converted to C# but gets an error.. It is used to to SELECT data from database with the use of LIKE for searching.. Here is my code:
public void byItemCode(ListView LV, String SearchBox)
{
try
{
con.Open();
ds.Tables.Add(dt);
OleDbDataAdapter da = new OleDbDataAdapter("SELECT ItemCode, Title, Genre, Film, YearReleased, Classification, NumberOfDiscs FROM tblDVDInventory WHERE ItemCode LIKE '%" + SearchBox + "%' ORDER BY Title", con);
da.Fill(dt);
int num = 1;
for (int ctr = 0; ctr <= dt.Rows.Count - 1; ctr++)
{
ListViewItem Item = new ListViewItem();
Item.Text = num;
Item.SubItems.Add(dt.Rows[ctr]["ItemCode"]);
Item.SubItems.Add(dt.Rows[ctr]["Title"]);
Item.SubItems.Add(dt.Rows[ctr]["Genre"]);
Item.SubItems.Add(dt.Rows[ctr]["Film"]);
Item.SubItems.Add(dt.Rows[ctr]["YearReleased"]);
Item.SubItems.Add(dt.Rows[ctr]["Classification"]);
Item.SubItems.Add(dt.Rows[ctr]["NumberOfDiscs"]);
LV.Items.Add(Item);
num = num + 1;
}
con.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
and then on the Search Form, here is the code:
var Search = new SearchMethods();
if (cmbSearchBy.Text == "Item Code")
{
lvwInventory.Items.Clear();
Search.byItemCode(lvwInventory, txtSearch.Text);
}
I wonder how to do this the right way in C#? Thanks.
Your Datatable will be filled with
Objects, notstrings.ListViewwantsstrings, so you need to callToString()or typecast tostringtype. UseToString()if you don’t know what types to expect or if you don’t expectstrings; use(string)casting if you expect astring.