Hiển thị dữ liệu lên listview C#

Đây là 1 số hàm thao tác với sqlite.

1. Đây là hàm insert level vào db , em có thể bỏ hàm checkExistLevel đi , tuỳ vào bài toán của em.

public void insertLevels[List levels]{ ContentValues values = new ContentValues[]; for [Level level: levels] { if [checkExistLevel[level.getLevelId[]]] continue; values.put[LEVEL_ID, level.getLevelId[]]; values.put[LEVEL_NAME, level.getLevelName[]]; values.put[LEVEL_CREATE_DATE, level.getLevelCreateDate[]]; mDatabase.insert[TABLE_LEVEL, null, values]; } }

2. Hàm check checkExistLevel

private boolean checkExistLevel[final int leveId] { String selectQuery = "SELECT * FROM " + TABLE_LEVEL + " WHERE " + LEVEL_ID + " = " + leveId; Cursor cursor = mDatabase.rawQuery[selectQuery, null]; if [cursor != null && cursor.getCount[] > 0] { return true; } return false; }

View Full Version : Đưa dữ liệu vào ListView trong lập trình C#?


skullrapper

24-04-2010, 05:29 PM

Chào mọi người hiện tại mình đang nghiên cứu 1 đồ án nhỏ bằng C#. Mình mong mọi người giúp mình vấn đề sau đây : 7529 Mình đã lưu được dữ liệu vào datagirdview rồi. Hôm nay mình muốn hỏi các bạn làm như thế nào để lưu dữ liệu vào ListView. Nghĩa là sau khi lưu dữ liệu xuống CSDL rồi thì ListView của mình sẽ Referesh lại và Load dữ liệu lên ngay sau khi nhấn vào button Lưu. - Với radiobutton thì mình lưu như thế nào ? Ở đây mình có radiobutton nam và nữ. - Với Combobox thì mình lưu xuống CSDL như thế nào .

Cảm ơn mọi người đã xem qua và giúp đỡ mình ! Có code càng tốt nhé các bạn [:P]

thach.thuc

24-04-2010, 06:09 PM

ListViewItem item = new ListViewItem[string colum1]; item.SubItems.Add[string colum2]; item.SubItems.Add[string colum3]; listViewname.Items.Add[item]; với radiobutton thì phải kiểm tra checked Ví dụ như bạn có nam và nữ thì bạn phải dùng một biến string sex; if [rdioNam.Checked] sex="Nam"; if[rdioNu.Checked] sex="Nu"; Còn cái câu "Với Combobox thì mình lưu như thế nào" mình không hiểu là bạn hỏi cách để add dữ liệu vào combobox hay là lưu dữ liệu từ combobox. nếu muốn lưu dữ liệu từ combobox thì

string a=comboBoxname.Items[index].ToString[];

skullrapper

25-04-2010, 12:29 AM

Hình như bạn hiểu sai câu hỏi mình r. Mình muốn sau khi nhập thông tin nhân viên r nhấn nút lưu thì dữ liệu đc lưu xuống CSDL đồng thời hiện lên ListView.

dieucay555

25-04-2010, 01:06 AM

Cứ add item bình thường thôi chứ nhẩy

tesulakata

26-04-2010, 08:13 PM

Hình như bạn hiểu sai câu hỏi mình r. Mình muốn sau khi nhập thông tin nhân viên r nhấn nút lưu thì dữ liệu đc lưu xuống CSDL đồng thời hiện lên ListView. Tớ chẳng biết như thế nào Tốt nhất bạn cho thêm code của "nút hiện dữ liệu" vào cùng với code phần lưu là xong chứ mấy * dù ko đươc tôi ưu cho lắm * < Nếu ko nhầm thì "nút hiện dữ liệu" trùng với phần code form load của bạn đấy > Chúc may mắn

[:-]h

huongthu12a4

26-04-2010, 08:26 PM

cái nút lưu dữ liệu,bạn viết sự kiện trong đó là 1 hàm kết nối đến cơ sở dữ liệu,viết 1 procedure để chèn thông tin mới nhé.gọi lại thủ tục đó và truyền các biến là các combobox,radiabutun ...nhé. Sau khi ấn lưu,bạn gọi lại hàm hiện thị lại dữ liệu là đc,dữ liệu sẽ tự cập nhật. ví dụ như bài mình nhé.Mình làm theo mô hình 3 lớp.Bạn nên tìm hiểu và làm theo cách đó,hay lắm,dễ sửa bài,gọn và dễ bắt lỗi. mình tạo 1 hàm để chèn như sau public void Ins_tblDichvu[string sqlQuery1, string sqlQuery2, string sqlQuery3,string sqlQuery4] { try { using [SqlConnection conn = new SqlConnection[source]] { conn.Open[]; SqlCommand cmd = new SqlCommand["ins_tblDichvu", conn]; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add[new SqlParameter["@madichvu", SqlDbType.Char,6, "madichvu"]]; cmd.Parameters.Add[new SqlParameter["@tendichvu", SqlDbType.NVarChar,25, "tendichvu"]]; SqlParameter sqlparameter = new SqlParameter[]; sqlparameter = new SqlParameter["@gia", sqlQuery3]; sqlparameter.SqlDbType = SqlDbType.Int; cmd.Parameters.Add[sqlparameter]; cmd.Parameters.Add[new SqlParameter["@donvitinh", SqlDbType.NVarChar, 10, "donvitinh"]]; cmd.UpdatedRowSource = UpdateRowSource.OutputParameters; cmd.Parameters["@madichvu"].Value = sqlQuery1; cmd.Parameters["@tendichvu"].Value = sqlQuery2; cmd.Parameters["@donvitinh"].Value = sqlQuery4; cmd.ExecuteNonQuery[]; conn.Close[]; conn.Dispose[]; } } catch [Exception e] { MessageBox.Show[e.Message]; } } sự kiện lưu như sau,thật ngắn gọn private void button1_Click[object sender, EventArgs e] { this.data.Ins_tblDichvu[tbmadichvu.Text.ToString[] ,tbtendichvu.Text.ToString[],tbgia.Text.ToString[] ,tbdonvitinh.Text.ToString[]]; this.data.Hienthi_tblDichvu[dataGridView1]; tbmadichvu.Text = ""; tbtendichvu.Text = ""; tbgia.Text = ""; tbdonvitinh.Text = ""; } hàm hiển thị bảng dịch vụ public void Hienthi_tblDichvu[DataGridView user] { try { using [SqlConnection conn = new SqlConnection[source]] { conn.Open[]; SqlDataAdapter cmd = new SqlDataAdapter["select *from tblDichvu", conn]; DataSet ds = new DataSet[]; cmd.Fill[ds, "tblDichvu"]; user.AutoGenerateColumns = false; user.Columns[0].DataPropertyName = "madichvu"; user.Columns[1].DataPropertyName = "tendichvu"; user.Columns[2].DataPropertyName = "gia"; user.Columns[3].DataPropertyName = "donvitinh"; user.DataSource = ds.Tables["tblDichvu"]; conn.Close[]; conn.Dispose[]; } } catch [Exception ex] { MessageBox.Show[ex.Message]; } }

Chúc bạn thành công

skullrapper

26-04-2010, 09:53 PM

cảm ơn mo người đã giúp mình

vBulletin® Version 4.2.2, Copyright © 2022 vBulletin Solutions, Inc. All rights reserved. Administer by Kevin Hoang

Tháng Một 11, 2019 nguyenvanquan7826 TUT Android Video Leave a response

Trong video này, mình hướng dẫn các bạn hiển thị dự liệu lên ListView

ListView là phần tử View được dùng để hiện thị dữ liệu là một danh sách [mảng] từ một nguồn cấp gọi là Adapter, các bước để tạo và sử dụng ListView gồm có:

Khai báo ListView trong Layout

Tương tự như các View khác, ví dụ:

Gán cho ListView một Adapter là nguồn cấp dữ liệu cho nó

Xây dựng một Adapter cho ListView ở phần dưới, sau khi có Adapter cần thiết lập cho ListView, ví dụ trong onCreate của Activity:

listViewProduct = findViewById[R.id.listproduct]; listViewProduct.setAdapter[productListViewAdapter];

Khi đã gán Adapter vào ListView, thì ListView sẽ dùng Adapter này xác định cần hiện thị bao nhiêu phần tử, mỗi phần tử có View như thế nào do Adapter tạo và đính vào ListView, mỗi khi dữ liệu Adapter quản lý thay đổi, cần thông báo cho ListView biết mà cập nhật bằng cách gọi:

adapter.notifyDataSetChanged[];

Xây dựng Adapter cho ListView

Như đã nói trên, Adapter là mô hình cung cấp dữ liệu cho ListView, nó có chức năng tạo các View phần tử, gán dữ liệu vào phần tử View con trong ListView. Để tạo ra một Adapter riêng chỉ cần kế thừa triển khai lớp trừu tượng BaseAdapter, trong đó cần overrided các phương thức như dưới đây [Ví dụ xây dựng lớp MyAdapter]:

class MyAdapter extends BaseAdapter { @Override public int getCount[] { //Cần trả về số phần tử mà ListView hiện thị return 0; } @Override public Object getItem[int position] { //Cần trả về đối tượng dữ liệu phần tử ở vị trí position return null; } @Override public long getItemId[int position] { //Trả về một ID liên quan đến phần tử ở vị trí position return 0; } @Override public View getView[int position, View convertView, ViewGroup parent] { //convertView là View hiện thị phần tử, nếu là null cần tạo mới //[có thể nạp từ layout bằng View.inflate] //Cuối cùng là gán dữ liệu ở vị trí possition vào View và trả về đối //tượng View này return null; } }

Ví dụ ListView trong Android

Nội dung Ví dụ

Ứng dụng hiện thị một danh sách các sản phẩm đơn giản, sản phẩm được trình bày trong một layout có các thông tin như ID, tên sản phẩm, giá. Khi bấm vào chọn một sản phẩm, Pop up lên thông báo tên sản phẩm đó. Có chức năng cho phép xoá phần tử đầu tiên của danh sách [sau khi xoá ListView cập nhật lại]

Khởi tạo Ví dụ

Chạy Android Studio và tạo ứng dụng đặt tên, ví dụ XTLabListView bằng mẫu Empty Activity, sau đó thay nội dung activity_main.xml thành giao diện đơn giản, riêng có ListView như sau:

Model dữ liệu sản phẩm

Mỗi sản phẩm đơn giản hiện thị ID, tên sản phẩm, giá nên ta tạo ra một mô hình dữ liệu của nó như sau:

//Model phần tử dữ liệu hiện class Product { String name; int price; int productID; public Product[int productID, String name, int price] { this.name = name; this.price = price; this.productID = productID; } }

Trong MainActivity tạo ra một mảng chứa dữ liệu mẫu các Product [dùng ArrayList], ví dụ:

ArrayList listProduct; //Mảng dữ liệu sản phẩm @Override protected void onCreate[Bundle savedInstanceState] { super.onCreate[savedInstanceState]; setContentView[R.layout.activity_main]; //Khoi tao ListProduct, tự sinh một số dữ liệu listProduct = new ArrayList[]; listProduct.add[new Product[1, "Iphone 6", 500]]; listProduct.add[new Product[2, "Iphone 7", 700]]; listProduct.add[new Product[3, "Sony Abc", 800]]; listProduct.add[new Product[4, "Samsung XYZ", 900]]; listProduct.add[new Product[5, "SP 5", 500]]; listProduct.add[new Product[6, "SP 6", 700]]; listProduct.add[new Product[7, "SP 7", 800]]; listProduct.add[new Product[8, "SP 8", 900]]; }

Tạo Adapter cho ListView hiện thị sản phầm

Adapter này xây dựng để liên kết với mảng dữ liệu sản phẩm ở trên [ArrayList listProduct], Adapter tạo ra các View để hiện thị sản phẩm, nên đầu tiên tạo ra layout hiện thị một sản phẩm trong listview, layout này được inflate khi cần thiết.

layout/product_view.xml [bạn có thể trành bày layout theo cách đẹp đẽ, phức tạp của bạn].

Giờ là lúc tạo ra Adapter, đặt tên lớp là ProductListViewAdapter, nội dung code như sau

class ProductListViewAdapter extends BaseAdapter { //Dữ liệu liên kết bởi Adapter là một mảng các sản phẩm final ArrayList listProduct; ProductListViewAdapter[ArrayList listProduct] { this.listProduct = listProduct; } @Override public int getCount[] { //Trả về tổng số phần tử, nó được gọi bởi ListView return listProduct.size[]; } @Override public Object getItem[int position] { //Trả về dữ liệu ở vị trí position của Adapter, tương ứng là phần tử //có chỉ số position trong listProduct return listProduct.get[position]; } @Override public long getItemId[int position] { //Trả về một ID của phần return listProduct.get[position].productID; } @Override public View getView[int position, View convertView, ViewGroup parent] { //convertView là View của phần tử ListView, nếu convertView != null nghĩa là //View này được sử dụng lại, chỉ việc cập nhật nội dung mới //Nếu null cần tạo mới View viewProduct; if [convertView == null] { viewProduct = View.inflate[parent.getContext[], R.layout.product_view, null]; } else viewProduct = convertView; //Bind sữ liệu phần tử vào View Product product = [Product] getItem[position]; [[TextView] viewProduct.findViewById[R.id.idproduct]].setText[String.format["ID = %d", product.productID]]; [[TextView] viewProduct.findViewById[R.id.nameproduct]].setText[String.format["Tên SP : %s", product.name]]; [[TextView] viewProduct.findViewById[R.id.priceproduct]].setText[String.format["Giá %d", product.price]]; return viewProduct; } }

Quay trở lại áp dụng, trong onCreate tạo ra đối tượng từ lớp ProductListViewAdapter [dữ liệu khởi tạo là mảng danh sách sản phẩm listProduct], biến Adapter này đặt tên là productListViewAdapter, sau đó gán nó cho ListView, đến đây thì ListView sẵn sàng hiện thị danh sách các sản phẩm của bạn!

Ngoài ra có thêm một số đoạn code tuỳ chọn như listViewProduct.setOnItemClickListener để bắt sự kiện khi bấm chọn một phần tử và bấm vào nút bấm để xoá phần tử đầu tiên. Code đầy đủ tổng hợp hoàn chỉnh lại của ứng dụng như sau:

MainActivity.java package net.xuanthulab.xtlablistview; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ArrayList listProduct; ProductListViewAdapter productListViewAdapter; ListView listViewProduct; @Override protected void onCreate[Bundle savedInstanceState] { super.onCreate[savedInstanceState]; setContentView[R.layout.activity_main]; //Khoi tao ListProduct listProduct = new ArrayList[]; listProduct.add[new Product[1, "Iphone 6", 500]]; listProduct.add[new Product[2, "Iphone 7", 700]]; listProduct.add[new Product[3, "Sony Abc", 800]]; listProduct.add[new Product[4, "Samsung XYZ", 900]]; listProduct.add[new Product[5, "SP 5", 500]]; listProduct.add[new Product[6, "SP 6", 700]]; listProduct.add[new Product[7, "SP 7", 800]]; listProduct.add[new Product[8, "SP 8", 900]]; productListViewAdapter = new ProductListViewAdapter[listProduct]; listViewProduct = findViewById[R.id.listproduct]; listViewProduct.setAdapter[productListViewAdapter]; //Lắng nghe bắt sự kiện một phần tử danh sách được chọn listViewProduct.setOnItemClickListener[new AdapterView.OnItemClickListener[] { @Override public void onItemClick[AdapterView parent, View view, int position, long id] { Product product = [Product] productListViewAdapter.getItem[position]; //Làm gì đó khi chọn sản phẩm [ví dụ tạo một Activity hiện thị chi tiết, biên tập ..] Toast.makeText[MainActivity.this, product.name, Toast.LENGTH_LONG].show[]; } }]; findViewById[R.id.delete].setOnClickListener[new View.OnClickListener[] { @Override public void onClick[View v] { if [listProduct.size[] > 0] { //Xoá phần tử đầu tiên của danh sách int productpost = 0; listProduct.remove[productpost]; //Thông báo cho ListView biết dữ liệu đã thay đổi [cập nhật, xoá ...] productListViewAdapter.notifyDataSetChanged[]; } } }]; } //Model phần tử dữ liệu hiện class Product { String name; int price; int productID; public Product[int productID, String name, int price] { this.name = name; this.price = price; this.productID = productID; } } class ProductListViewAdapter extends BaseAdapter { //Dữ liệu liên kết bởi Adapter là một mảng các sản phẩm final ArrayList listProduct; ProductListViewAdapter[ArrayList listProduct] { this.listProduct = listProduct; } @Override public int getCount[] { //Trả về tổng số phần tử, nó được gọi bởi ListView return listProduct.size[]; } @Override public Object getItem[int position] { //Trả về dữ liệu ở vị trí position của Adapter, tương ứng là phần tử //có chỉ số position trong listProduct return listProduct.get[position]; } @Override public long getItemId[int position] { //Trả về một ID của phần return listProduct.get[position].productID; } @Override public View getView[int position, View convertView, ViewGroup parent] { //convertView là View của phần tử ListView, nếu convertView != null nghĩa là //View này được sử dụng lại, chỉ việc cập nhật nội dung mới //Nếu null cần tạo mới View viewProduct; if [convertView == null] { viewProduct = View.inflate[parent.getContext[], R.layout.product_view, null]; } else viewProduct = convertView; //Bind sữ liệu phần tử vào View Product product = [Product] getItem[position]; [[TextView] viewProduct.findViewById[R.id.idproduct]].setText[String.format["ID = %d", product.productID]]; [[TextView] viewProduct.findViewById[R.id.nameproduct]].setText[String.format["Tên SP : %s", product.name]]; [[TextView] viewProduct.findViewById[R.id.priceproduct]].setText[String.format["Giá %d", product.price]]; return viewProduct; } } }

Ví dụ này lưu tại //github.com/xuanthulabnet/android-listview-example, có thể tải vể bằng lệnh Git: git clone :xuanthulabnet/android-listview-example.git

Video liên quan

Chủ Đề