This code snippet shows how to develop a simple DataList control, that can be used to present data in a list format.
DataList.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Data;
using System.Drawing;
namespace SimpleDataPagerDemo
{
class DataList : Panel
{
private DataTable _dataTable;
private TableLayoutPanel _tlp = new TableLayoutPanel();
public DataTable DataTable
{
get { return this._dataTable; }
set { this._dataTable = value; }
}
public DataList()
{
_tlp.BackColor = Color.Black;
_tlp.CellPaint += new TableLayoutCellPaintEventHandler(_tlp_CellPaint);
}
void _tlp_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
if (e.Row % 2 == 0)
{
e.Graphics.FillRectangle(Brushes.LightSteelBlue, e.CellBounds);
}
else
{
e.Graphics.FillRectangle(Brushes.SteelBlue, e.CellBounds);
}
}
public void Bind()
{
this._tlp.Controls.Clear();
int columns = this._dataTable.Columns.Count;
int idxRow = 0;
_tlp.ColumnCount = columns;
_tlp.AutoSize = true;
_tlp.Visible = false;
foreach (DataRow row in this._dataTable.Rows)
{
for (int i = 0; i < columns; i++)
{
Label lblColumn = new Label();
lblColumn.AutoSize = true;
lblColumn.Text = row[i].ToString();
lblColumn.BackColor = Color.Transparent;
lblColumn.Padding = new System.Windows.Forms.Padding(5);
_tlp.Controls.Add(lblColumn, i, idxRow);
}
idxRow++;
this.Controls.Add(_tlp);
}
_tlp.Visible = true;
this.AutoScroll = true;
}
}
}
Form Load
private void Form1_Load(object sender, EventArgs e)
{
DataTable empTable = new DataTable();
empTable.Columns.Add("EmployeeId");
empTable.Columns.Add("FirstName");
empTable.Columns.Add("LastName");
empTable.Columns.Add("Email");
empTable.Rows.Add("1", "John", "Smith", "j.smith@mail.com");
empTable.Rows.Add("2", "Ted", "Baker", "t.baker@mail.com");
empTable.Rows.Add("3", "Suzan", "Smith", "s.smith@mail.com");
empTable.Rows.Add("4", "Larry", "Jones", "l.jones@mail.com");
empTable.Rows.Add("5", "Linda", "Baker", "l.baker@mail.com");
DataList list = new DataList();
list.DataTable = empTable;
list.AutoSize = true;
list.Bind();
this.Controls.Add(list);
}
No comments:
Post a Comment