[英]How to bind datalist from code behind in asp.net
我想從asp.net中的代碼后面綁定數據列表
我從列表中獲取產品ID,然后根據其基礎選擇所有產品
以下是我的代碼:
List<string> r_items_grid = (List<string>)Session["recent_items"];
for(int i=0; i < r_items_grid.Count; i++)
{
OleDbCommand cmd_r_items= new OleDbCommand("SELECT product_id,product_name,product_price,product_image_1 from products where product_id="+ Convert.ToInt32( r_items_grid[i]),con);
r_items_reader=cmd_r_items.ExecuteReader();
DataList3.DataSource = r_items_reader;
DataList3.DataBind();
}
但是我只看到數據列表中的最后一條記錄
問題是您一次選擇一個記錄,然后將其分配給數據源。 執行該操作時,先前的值將被覆蓋。 因此,您只能看到上一次查詢的結果。 您可以通過發出單個請求,然后將其綁定到列表來解決此問題:
下面的代碼在假定您知道Session["recent_items"]
存儲整數的情況下Session["recent_items"]
,如果有可能在其中存儲字符串,則存在SQL注入的風險。
List<string> r_items_grid = (List<string>)Session["recent_items"];
string ids = string.Join(",", r_items_grid); // Here you get IDs in format 1,2,3,4,5 etc.
OleDbCommand cmd_r_items= new OleDbCommand("SELECT product_id,product_name,product_price,product_image_1 from products where product_id IN ("+ ids + ")",con);
r_items_reader=cmd_r_items.ExecuteReader();
DataList3.DataSource = r_items_reader;
DataList3.DataBind();
如果我沒有記錯,您嘗試將字符串列表放入會話中。 每次遍歷整個列表時,都將數據列表(DataList3)與基於列表索引值的新字符串綁定在一起。 因此,它始終顯示列表的最后一個字符串值。 如果要根據列表獲取所有數據,則可以使用此方法
List<string> r_items_grid = (List<string>)Session["recent_items"];
string items_id= string.Join(",", r_items_grid);// items_id may be like 1,2,3,4,5.
OleDbCommand cmd_r_items= new OleDbCommand("SELECT product_id,product_name,product_price,product_image_1 from products where product_id IN ("+ items_id + ")",con);
r_items_reader=cmd_r_items.ExecuteReader();
DataList3.DataSource = r_items_reader;
DataList3.DataBind();
查詢用於從product_id為(1,2,3,4,5 ...)的產品中選擇SELECT product_id,product_name,product_price,product_image_1。該查詢用於獲取item_id為1,2,3,4,5的所有數據。 ..
無需循環
您可以使用逗號分隔的列表
string commaSepara = String.Join(",", r_items_grid);
OleDbParameters commaSepara=new OleDbParameters("@commaSepara",SqlDbType.NVarchar,-1);
commaSepara.Value=commaSepara;
OleDbCommand cmd_r_items= new OleDbCommand(@"SELECT product_id,product_name,product_price,product_image_1 from products where product_id
IN ( @commaSepara )",con);
r_items_reader=cmd_r_items.ExecuteReader();
DataList3.DataSource = r_items_reader;
DataList3.DataBind();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.