Đánh số thứ tự trong ListView C#

Bài viết hôm nay hướng dẫn các bạn tạo cột số thứ tự tự động tăng cho từng dòng và group dữ liệu trong GridControl. Việc tạo cột số thứ tự này sẽ giúp bạn dễ dàng xác định vị trí của dòng dữ liệu trên GridView hơn, nếu có thêm Group thì lúc đó GridView của bạn nhìn sẽ gọn và hợp lý hơn. Sau đây là bài hướng dẫn chi tiết:(Các bạn có thể phải triển thêm bằng các tạo ra 1 GridControl mới có sẵn cột số thứ tự, nếu không biết tạo control mới từ control có sẵn qua bài viết sau: Phần 1)

Đánh số thứ tự trong ListView C#

B1. Các thư viện mới sử dụng trong chương trình

using DevExpress.XtraGrid.Views.Grid;

B2. Sự kiện được sử dụng để vẽ cột số thứ tự

gridView1.CustomDrawRowIndicator += gridView1_CustomDrawRowIndicator;

B3. Viết sự kiện

void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e) { if (!gridView1.IsGroupRow(e.RowHandle)) //Nếu không phải là Group { if (e.Info.IsRowIndicator) //Nếu là dòng Indicator { if (e.RowHandle < 0) { e.Info.ImageIndex = 0; e.Info.DisplayText = string.Empty; } else { e.Info.ImageIndex = -1; //Không hiển thị hình e.Info.DisplayText = (e.RowHandle + 1).ToString(); //Số thứ tự tăng dần } SizeF _Size = e.Graphics.MeasureString(e.Info.DisplayText, e.Appearance.Font); //Lấy kích thước của vùng hiển thị Text Int32 _Width = Convert.ToInt32(_Size.Width) + 20; BeginInvoke(new MethodInvoker(delegate { cal(_Width, gridView1); })); //Tăng kích thước nếu Text vượt quá } } else { e.Info.ImageIndex = -1; e.Info.DisplayText = string.Format("[{0}]",(e.RowHandle *-1)); //Nhân -1 để đánh lại số thứ tự tăng dần SizeF _Size = e.Graphics.MeasureString(e.Info.DisplayText, e.Appearance.Font); Int32 _Width = Convert.ToInt32(_Size.Width) + 20; BeginInvoke(new MethodInvoker(delegate { cal(_Width, gridView1); })); } }

B4. Hàm để tăng kích thước của Indicator khi có thay đổi về giá trị của RowHandle

bool cal(Int32 _Width,GridView _View) { _View.IndicatorWidth = _View.IndicatorWidth < _Width ? _Width : _View.IndicatorWidth; return true; }

Và dưới đây là video hướng dẫn chi tiết

Cảm ơn các bạn đã quan tâm theo dõi. Hãy Like Share để ủng hộ nha các bạn !

THÔNG TIN TÁC GIẢ

Đánh số thứ tự trong ListView C#
FreeLancer 37 bài viết 492,205

Freelance Full-Stack Developer - Admin at LaptrinhVB.net
- Skills: .NET (C#, VB.NET), MSSQL, DevExpress, ReactJs, NodeJs, Angular, ThreeJs, MongoDB,....
- Our Services:

  • Software development (ERP - Enterprise Resource Planning, HRM - Human Resource Management, CRM - Customer Relationship Management, SCM - Supply Chain Management, Finance, ...)
  • Web/App design & development

- Phone/Zalo/Viber: 090.698.1755 (Mr. Băng)
- Email/Skype:

BÀI VIẾT LIÊN QUAN

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ụ:

<ListView android:id="@+id/listproduct" android:layout_width="match_parent" android:layout_height="match_parent" /> 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)

Đánh số thứ tự trong ListView C#

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:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:orientation="vertical"> <ListView android:id="@+id/listproduct" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <Button android:id="@+id/delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Xoá sản phẩm đầu tiên" /> </LinearLayout>

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<Product> 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<Product> 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). <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="20dp"> <TextView android:id="@+id/idproduct" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="1" /> <TextView android:id="@+id/nameproduct" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="ProductName" android:textStyle="bold" /> <TextView android:id="@+id/priceproduct" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="right" android:text="1000" /> </LinearLayout>

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<Product> listProduct; ProductListViewAdapter(ArrayList<Product> 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<Product> 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<Product> listProduct; ProductListViewAdapter(ArrayList<Product> 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; } } }

Đánh số thứ tự trong ListView C#

Đánh số thứ tự trong ListView C#

Đánh số thứ tự trong ListView C#

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