从列表填充列表框
问题描述:
我在这里丢失了一些非常简单的东西......我已经通过我的调试器并且一切正常,但ListBox没有被填充新数据。当我运行网站时它显示为空白。从列表填充列表框<string>
我想:
STEP.1填充从我的数据库文件路径字符串列表框。 (这是可以的)
Step.2使用ListBox项目创建一个新List,从进程中的每个字符串中删除路径。 (这似乎是好的,当我调试时,count
正在增加list
)
Step.3使用我的新'列表'重新填充ListBox。 (不工作)
<div>
<asp:ListBox ID="ListBox1" runat="server" Width="100%" Height="100%" AutoPostBack="true"/>
</div>
检索数据库中的文件路径和填充数据表(这是确定)
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;
}
指定的DataTable到列表框(这是确定)。
从列表框中删除每个项目并删除路径,只留下finalFileName
(这是可以的)。
分配finalFileName
到list
(我认为这是好的,“计数”在调试增加)
分配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
操纵数据,只需使用以下命令,然后将其绑定到你的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();
}
您是否尝试过添加ListBox1.DataBind();在ListBox1.DataSource = list之后的 ; ? 我认为应该做的伎俩 –
我有,它引发了我的声明,但我不知道为什么。 (有一个try/catch没有显示) – DMur
什么是例外? 也尝试放列表 list = new List ();在...之前... –