初级问题,listBox如何绑定数据
如题:
我要绑定的是一个类组。
比如我有一个Player类
Player[] myPlayer=new Player[4];
这个Player类里有姓名,性别,职称。等等。
[解决办法]
DataTable dt = new DataTable( "Staff ");
DataColumn dc;
dc = new DataColumn( "ID ", System.Type.GetType( "System.Int32 "));
dt.Columns.Add(dc);
dc = new DataColumn( "BeginDate ", System.Type.GetType( "System.DateTime "));
dt.Columns.Add(dc);
dc = new DataColumn( "EndDate ", System.Type.GetType( "System.DateTime "));
dt.Columns.Add(dc);
dc = new DataColumn( "Company ", System.Type.GetType( "System.String "));
dt.Columns.Add(dc);
dc = new DataColumn( "Department ", System.Type.GetType( "System.String "));
dt.Columns.Add(dc);
dc = new DataColumn( "Manager ", System.Type.GetType( "System.String "));
dt.Columns.Add(dc);
dc = new DataColumn( "Telephone ", System.Type.GetType( "System.String "));
dt.Columns.Add(dc);
DataRow dr;
dr = dt.NewRow();
dr[ "ID "] = 1;
dr[ "BeginDate "] = System.DateTime.Today;
dr[ "EndDate "] = System.DateTime.Today;
dr[ "Company "] = "×××× ";
dr[ "Department "] = "×××× ";
dr[ "Manager "] = "×× ";
dr[ "Telephone "] = "654321 ";
dt.Rows.Add(dr);
dgWork.DataSource = dt;
dgWork.DataBind();
--------------
DataTable WorkTable = ds.Tables.Add( "TableName ");//建立表 TableName=表名
for(int i = 0; i < Count; i++)//建表
{
DataColumn myColumn = new DataColumn();
myColumn.DataType = typeof(object);
myColumn.Caption = " "; myColumn.ColumnName = " "
WorkTable.Columns.Add(myColumn);
}
this.dlbF.DataSource = dsSource.Tables[0].DefaultView;
this.dlbF.DataTextField = " ";
this.dlbF.DataValueField = " ";
this.dlbF.DataBind();
-------------
DataTable tbTest = new DataTable(); // 新建一个DataTable
// 给Table定义添加Column
DataColumn col;
col = new DataColumn( "id ",typeof(int));
tbTest.Columns.Add(col);
col = new DataColunm( "title ",typeof(string));
col.MaxLength = 50; // 设置字段长度
tbTest.Columns.Add(col);
// 设置主键
tbTest.PrimaryKey = new DataColumn[]{tbTest.Columns[ "id "]};
// 添加数据
DataRow row = tbTest.NewRow();
row[ "id "] = 1;
row[ "title "] = "第一条记录 ";
tbTest.Rows.Add(row);
// 设置主键 一些方法会用到主键的
tbTest.PrimaryKey = new DataColumn[]{tbTest.Columns[ "id "]};
[解决办法]
string[] ary = new string[] { "A ", "B ", "C " }; this.DropDownList1.DataSource = ary; this.DropDownList1.DataBind();
------解决方案--------------------
cpp2017(慕白兄) 只是告诉你的绑定方法,并不是让你直接用
比如我有一个Player类
Player[] myPlayer=new Player[4];
这个Player类里有姓名,性别,职称。等等。
----------------------------------------------
不知道你要显示的是什么,如果显示姓名
ListBox1.DataTextField = "姓名 "; //属性的名字
ListBox1.DataValueField = "编号 ";
ListBox1.DataSource = myPlayer;
ListBox1.DataBind();