[英]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.