繁体   English   中英

从列表填充ListBox <string>

[英]Populate ListBox from List<string>

我在这里遗漏了一些非常简单的内容...我逐步调试了一下,一切正常,但是ListBox并未填充新数据。 当我运行网站时,它显示为空。

我想要:

步骤1用我数据库中的文件路径字符串填充列表框。 (还行吧)

Step.2使用ListBox项目创建一个新List,从过程中的每个字符串中删除路径。 (这似乎还可以,调试时list count在增加)

Step.3使用我的新“列表”重新填充ListBox。 (不工作)

<div>
<asp:ListBox ID="ListBox1" runat="server" Width="100%" Height="100%" AutoPostBack="true"/>
</div>

从数据库中检索文件路径并填充DataTable:(可以)

private DataTable loadUserImageNames()
{
    string cpUsersConnection1 = ConfigurationManager.ConnectionStrings["cp_usersConnection"].ToString();
    SqlConnection oSqlConnection1 = new SqlConnection(cpUsersConnection1);
    oSqlConnection1.Open();
    SqlCommand oSqlCommand1 = new SqlCommand();
    oSqlCommand1.Connection = oSqlConnection1;
    oSqlCommand1.CommandType = CommandType.Text;
    oSqlCommand1.CommandText = "SELECT FilePath from User_Images where AcNo ='" + AcNo.Text + "' ORDER BY AcNo";
    SqlDataAdapter oSqlDataAdapter1 = new SqlDataAdapter();
    oSqlDataAdapter1.SelectCommand = oSqlCommand1;
    DataTable oDataTable1 = new DataTable("User_Images");
    oSqlDataAdapter1.Fill(oDataTable1);
    return oDataTable1;
}

将数据表分配给列表框(可以)。

从ListBox调出每个项目并删除Path,仅finalFileName (这是可以的)。

finalFileName分配给list (我认为可以,调试中'count'不断增加)

list分配给ListBox1 ....这不起作用,ListBox1为空。

if (!Page.IsPostBack)
{
    DataTable oDataTable1 = loadUserImageNames();
    ListBox1.DataSource = oDataTable1;
    ListBox1.DataTextField = "FilePath";
    ListBox1.DataBind();

    List<string> list = new List<string>();

    foreach (ListItem s in ListBox1.Items)
    {
        string filePath = (s.ToString());
        string finalFileName = (filePath.Substring(filePath.LastIndexOf('/') + 1));
        list.Add(finalFileName);
    }
    ListBox1.DataSource = list;
}

您不需要创建list来处理数据,只需使用following并将其绑定到ListBox控件即可。 我已经将FilePath视为将从数据库中检索的列名。

if (!Page.IsPostBack)
 {
     DataTable oDataTable1 = loadUserImageNames();
     foreach (DataRow dr in oDataTable1.Rows)
     {
         string filePath = (dr.Field<string>("FilePath"));
         string finalFileName = (filePath.Substring(filePath.LastIndexOf('/') + 1));
         dr["FilePath"] = finalFileName;
         // Or you can use following
         // dr["FilePath"] = (filePath.Substring(filePath.LastIndexOf('/') + 1)); // In One Line 
     }
     ListBox1.DataSource = oDataTable1;
     ListBox1.DataTextField = "FilePath";
     ListBox1.DataBind();
 }

暂无
暂无

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

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