Insert into ListBox from a Database
Question: How can I insert items into a listbox from a database?
Here is what I tried:
public void Fetch()
{
using (SqlConnection cn = new
SqlConnection(UtilObj.ConnectionString()))
{
cn.Open();
ExecuteFetch(cn);
cn.Close();
}
}
public void ExecuteFetch(SqlConnection cn)
{
ListBox myListBox = new ListBox();
myListBox.FindControl("myListBox");
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "spName";
cm.Parameters.AddWithValue("@Param1", Param1Val);
using (SafeDataReader dr = new
SafeDataReader(cm.ExecuteReader()))
{
while (dr.Read())
{
// This is where I tried two different things...
// myListBox.Text = dr["Color"].ToString();
myListBox.Items.Add(dr["Color"].ToString());
}
}
}
}
Both show the same empty list when I run the code.
Here is how I define my listbox:
ListBox myListBox = new ListBox();
myListBox.FindControl("myListBox");
No comments:
Post a Comment