无法在asp.net web应用程序中填充lsitbox

本文关键字:应用程序 填充 lsitbox web net asp | 更新日期: 2023-09-27 18:09:44

我试图从SQL数据库中的客户表填充列表框。我用WPF列表框测试了代码工作良好,但当我尝试在asp.net web应用程序中实现时,我无法填充列表框。这是我的代码

 try
            {
                string query = "SELECT customer_ID FROM Customers WHERE ID = 1";
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
                conn.Open();
                SqlDataAdapter da = new SqlDataAdapter(query , conn);
                da.Fill(ds);
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    listbox1.SelectedValue = row["customer_ID"].ToString();
                    samplelist.Add(listbox1.SelectedValue);
                }
                listbox1.DataSource = samplelist;
            }
            catch (Exception)
            {
            }
有谁能给我指路吗?

无法在asp.net web应用程序中填充lsitbox

尝试使用下面的代码:

        try
        { 
            string query = "SELECT customer_ID FROM Customers WHERE ID = 1"; 
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()); 
            conn.Open(); 
            SqlDataAdapter da = new SqlDataAdapter(query, conn); 
            da.Fill(ds);
            listbox1.DataSource = ds.Tables[0];
            listbox1.DataTextField = "WORKSTATION_ID";
            listbox1.DataValueField = "WORKSTATION_ID";
            listbox1.DataBind();
        }
        catch (Exception) 
        { 
        }
        foreach (DataRow row in ds.Tables[0].Rows)
            {
                samplelist.Add(row["WORKSTATION_ID"].ToString());
            }
            listbox1.DataSource = samplelist;
    listbox1.DataBind();

您应该能够将其缩减为以下内容。您还遗漏了DataBind():

try
{
//Existing to fill ds, check table exists, etc.
listbox1.DataSource = ds.Tables[0];
listbox1.DataValueField = "COLUMNNAME";
listbox1.DataTextField = "COLUMNNAME";
listbox1.DataBind();
}
catch (Exception)
{
}