sibotho 0 Light Poster

Hi

I have a database with a Contacts table, in this table I have 2 columns emailAdd and byEmail. I want to select emailAdd where byEmail = Y and add these selected items into a Listbox.

Please help how do i do this

this is what I tried but does not work.

SqlDataSource notify = new SqlDataSource();
        notify.ConnectionString = ConfigurationManager.ConnectionStrings["procurementConnectionString5"].ToString();
        
        notify.SelectCommandType = SqlDataSourceCommandType.Text;
        notify.SelectCommand = "SELECT emailAdd FROM ContactDetails WHERE byEmail LIKE 'Y'";  //not sure about this line as well                             

        string []item = {notify.SelectParameters.ToString()}; // I think the problem is with this line

        foreach (string ss in item)
        {
            //ListBox1.DataBind();
            ListBox1.Items.Add(ss);
          
        }

Dani AI

Generated

Short answer for : the code in the original post never executes the query or reads rows — calling SelectParameters.ToString() just returns parameter metadata, not the result set. Two reliable approaches follow: (A) run the query with ADO.NET and read rows with a SqlDataReader, or (B) call SqlDataSource.Select(...) (it returns a DataView) and bind that to the ListBox. Do this only on the initial page load to avoid duplicated items.

// A — ADO.NET (do this inside if (!IsPostBack) on Page_Load)
string conn = ConfigurationManager.ConnectionStrings["yourConnectionStringName"].ConnectionString;
using (SqlConnection cn = new SqlConnection(conn))
{
    cn.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT emailAdd FROM ContactDetails WHERE byEmail = @flag", cn))
    {
        cmd.Parameters.AddWithValue("@flag", "Y");
        using (SqlDataReader rdr = cmd.ExecuteReader())
        {
            while (rdr.Read())
            {
                ListBox1.Items.Add(rdr.GetString(0));
            }
        }
    }
}
// B — using the SqlDataSource instance already created
DataView dv = (DataView)notify.Select(DataSourceSelectArguments.Empty);
ListBox1.DataSource = dv;
ListBox1.DataTextField = "emailAdd";
ListBox1.DataBind();

Troubleshooting and gotchas: confirm the connection string name is correct; verify the actual stored values in byEmail (char 'Y' versus bit/boolean); test the SELECT in SQL Server Management Studio; wrap population code in if (!IsPostBack); trim or null-check emailAdd before adding; prefer parameterized SQL to avoid injection and mismatches. For reference on the APIs used, see the Microsoft docs for SqlDataReader, SqlDataSource.Select and ListBox.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.