繁体   English   中英

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

[英]Unable to populate lsitbox in asp.net web application

我正在尝试从SQL数据库中的customers表填充列表框。我使用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)
            {
            }

任何人都能引导我朝着正确的方向前进吗?

尝试使用以下代码:

        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)
{
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM