Binding a GridView Programmatically

G

Guest

I've seen how to set up a gridview at design time, but I believe I need to do
this and run time and cannot figure it out. I am sending a concatenated list
of IDs that is gets bigger each time a user enters another ID. The code to
get the data back is below and it works and I am returning an ArrayList. I
get an error when I bind the gridview control:

-- A field or property with the name 'ItemName' was not found on the
selected data source. --

I have the grid defined with one column, named "ItemName". Can someone tell
me what I am doing wrong and show me where to fix it? Thank you.

//Code in the code behind page that is calling the method below it.
gridview1.DataSource = Media.Lookup((ArrayList)Session["Media"]);
gridview1.DataBind();


public static ArrayList Lookup(ArrayList mediaID)
{
string mediaIDs = string.Empty;

for (int x = 0; x <= mediaID.Count - 1; x++)
{
mediaIDs += mediaID[x].ToString() + ",";
}
mediaIDs = mediaIDs.Substring(0, mediaIDs.Length - 1);

using (SqlConnection conn = new SqlConnection(connectionString))
{

using (SqlCommand command = new SqlCommand("GetMedia", conn))
{
command.CommandType = System.Data.CommandType.StoredProcedure;

SqlParameter param;
param = command.Parameters.Add("@inventoryIDs",
System.Data.SqlDbType.VarChar,
50);
param.Value = mediaIDs;

SqlDataReader dataReader;
conn.Open();
dataReader = command.ExecuteReader();
ArrayList titles = new ArrayList();
while (dataReader.Read())
{
titles.Add(dataReader["ItemName"].ToString());
}

return titles;
}
}
 
E

Eliyahu Goldin

Instead of databinding to an ArrayList, do directly to the datareader:

gridview1.DataSource = dataReader;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top