使用数组列表绑定表数据字段 [英] bind table datafield using array list
问题描述
al = new ArrayList();
al.Add(test);
al.Add(test1);
GridView1.DataSource = al;
GridView1.DataBind();
我想要的是代替al.Add()中的test和test1;我想从数据库中绑定表的dataField.?
what i want is in place of test and test1 in al.Add(); i want to bind the dataField of table from a database.?
推荐答案
要从数据库中绑定表的dataField.
根据您的操作,您有两种选择:
1.将从数据库检索到的数据表直接绑定到网格.
2.找到特定的值,然后将其添加到arraylist中,例如:
want to bind the dataField of table from a database.
Based on what you are doing you have two options:
1. Directly bind the datatable that is retrieved from DB to grid.
2. Find the specific values and then add that to the arraylist, something like:
// Find the row and column and use it
// Assuming 1st row - 2 columns
al.Add(MyDataTable.Row[0]["Column1"].ToString());
al.Add(MyDataTable.Row[0]["Column2"].ToString());
答案2很好.
我有一个小建议.
ArrayList
是非通用类型.这意味着存在no type safety
,即在上面的示例中
Answer 2 is good.
I have a small suggestion.
ArrayList
is non generic type. Which means there isno type safety
, i.e. in the above example
a1.Add("Test");
a1.Add(5);
都可以使用,但是如果所需的类型仅是string or int
,则可以使用throw error at run time
.
其次,当与value types
一起使用时,如果是非泛型类型,则会有一个overhead of boxing and unboxing
.
因此,最好使用ArrayList
的Generic
计数器部分. List<T>
在这里解释 http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx [ ^ ],作者:如解决方案2中所示,使用数据库中的值填充它.
对于问题中显示的情况,在GridView
中仅使用一列,在这种情况下,除非有特殊要求使用GridView
,否则我认为ListBox
可以是轻量级控件.
如果需要使用GridView
,尤其是多于一列的情况下,我认为最好使用DataTable
.
will both work but it will throw error at run time
if the required type is say either string or int
only.
Secondly, when used with value types
in case of non generic types there is an overhead of boxing and unboxing
.
So, it is better to use the Generic
counter part of ArrayList
i.e. List<T>
explained here http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx[^], by populating it with the values from the DB as already shown in Solution 2.
For the case shown in the question only one column is being used in the GridView
in which case I think a ListBox
can be lightweight control unless there is a specific requirement to use a GridView
.
In case GridView
is required to be used, in particular with more than one column, I think it is better to use a DataTable
.
这篇关于使用数组列表绑定表数据字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!