Click here to Skip to main content
14,693,774 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
al = new ArrayList();
        al.Add(test);
        al.Add(test1);
        GridView1.DataSource = al;
        GridView1.DataBind();


what i want is in place of test and test1 in al.Add(); i want to bind the dataField of table from a database.?
Posted
Updated 30-May-12 4:05am
v2

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());
   
Comments
VJ Reddy 30-May-12 9:29am
   
Good answer. 5!
Sandeep Mewara 30-May-12 14:34pm
   
Thanks VJ.
Maciej Los 30-May-12 16:12pm
   
Good answer, my 5!
Sandeep Mewara 30-May-12 16:21pm
   
Thanks.
Answer 2 is good.

I have a small suggestion.

ArrayList is non generic type. Which means there is no type safety, i.e. in the above example
a1.Add("Test");
a1.Add(5);

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 GridViewin 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.
   
v3
Comments
Maciej Los 30-May-12 16:12pm
   
Very good answer, my 5!
VJ Reddy 30-May-12 19:52pm
   
Thank you very much, losmac :)
Sandeep Mewara 30-May-12 16:21pm
   
Good suggestion! 5!
VJ Reddy 30-May-12 19:52pm
   
Thank you very much, Sandeep :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900