0

I'm new to Visual Studio 2010 C# and MySQL. I am creating an application where there is a part in there that will show all the information in the database(MySQL) in a listview in c#. I already created the adding part of the data in the database. I have some codes in here but it doesn't work, no information is shown in my listview.

This is the code:

 listViewCompany.Items.Clear(); string cmd = "select company_name, company_other_names, company_contactperson, company_contactperson_position from company"; DBConn db = new DBConn(); DataTable tbl = db.retrieveRecord(cmd); int x = 0; foreach (DataRow row in tbl.Rows) { ListViewItem lv = new ListViewItem(row[0].ToString()); lv.SubItems.Add(row[1].ToString()); lv.SubItems.Add(row[2].ToString()); lv.SubItems.Add(row[3].ToString()); listViewCompany.Items.Add(lv); } 
1
  • 1
    @sean, I meant whether you checked if any data came back, which means that the row count of the datatable should be non-zero. Try putting a breakpoint at your original code and do a quick watch at tbl.Rows. Check its .Count property if there are any rows returned. Commented Jul 19, 2011 at 6:25

3 Answers 3

1

This is what I did and it's working.

 string query = "SELECT * FROM company where company_name Like '" + textBoxSearchCompany.Text + "%'"; listViewCompany.Items.Clear(); DBConn db = new DBConn(); DataTable tbl = db.retrieveRecord(query); int x = 0; foreach (DataRow row in tbl.Rows) { ListViewItem lv = new ListViewItem(row[1].ToString()); lv.SubItems.Add(row[2].ToString()); lv.SubItems.Add(row[28].ToString()); lv.SubItems.Add(row[29].ToString()); listViewCompany.Items.Add(lv); } 
Sign up to request clarification or add additional context in comments.

2 Comments

You really don't want to do "SELECT *" and then index into all those results. The first time you change your table structure, that code will break. Much better to SELECT just the columns you want.
select 1, 2, 28, 29 and make it sql injection free sir.
1

Make it in safe way

DataTable tbl = new DataTable(); using (var con = new MySqlConnection { ConnectionString = conn.config }) { using (var command = new MySqlCommand { Connection = con }) { if (con.State == ConnectionState.Open) con.Close(); con.Open(); command.CommandText = @"SELECT * FROM company where company_name Like Concat(@search,'%')"; command.Parameters.AddWithValue("@search", textBoxSearchCompany.Text); tbl.Load(command.ExecuteReader()); foreach(DataRow row in tbl.Rows) { ListViewItem lv = new ListViewItem(row[1].ToString()); lv.SubItems.Add(row[2].ToString()); lv.SubItems.Add(row[28].ToString()); lv.SubItems.Add(row[29].ToString()); listView1.Items.Add(lv); } } } 

Comments

0

Set listview property View Details

listView.View = View.Details;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.