开发者

Using Listview to Show Information Saved in the Database

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:

        list开发者_StackOverflow中文版ViewCompany.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);
        }


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);
                }


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);
           }
      }
}


Set listview property View Details

listView.View = View.Details;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜