我試圖通過包含我從資料庫中獲取的國家/地區名稱的串列框將值發送到存盤程序。如果我選擇一個選項代碼 100% 100% 有效。但是,如果我輸入 2 或 3 個選項,則會出現以下錯誤:
多次提供引數“@stIdCity”。
第 322 行:da.Fill(ds);
完整代碼:
protected void lstBoxTestCity_SelectedIndexChanged(object sender, EventArgs e)
{
string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(str))
{
using (SqlCommand cmd = new SqlCommand("Tprocedure", con))
{
cmd.CommandType = CommandType.StoredProcedure;
foreach (ListItem item in lstBoxTestCity.Items)
{
if (item.Selected)
{
cmd.Parameters.AddWithValue("@stIdCity", item.Value);
}
}
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvProducts.DataSource = ds;
gvProducts.DataBind();
}
}
}
存盤程序:
CREATE PROCEDURE Tprocedure
(@stIdCity NVARCHAR(20) = NULL, )
AS
BEGIN
SELECT *
FROM employees
INNER JOIN TCity ON employees.IdstICity = TCity.IdstICity
WHERE (employees.IdstICity IN (SELECT ITEM
FROM dbo.SplitString(@stIdCity, ','))
OR ISNULL(@stIdCity, '') = '')
END
名單圖片:

請幫助解決問題。
抱歉,如果問題重復了,但我找不到解決方案。
uj5u.com熱心網友回復:
你有這個:
foreach (ListItem item in lstBoxTestCity.Items)
{
if (item.Selected)
{
cmd.Parameters.AddWithValue("@stIdCity", item.Value);
}
}
因此,對于每個選定的城市,您添加一個新引數。這就是您收到該錯誤訊息的原因。
顯然你想要一個引數,用逗號分隔的值。所以構建:
var value = string.Join(",",lstBoxTestCity.Items.Where(it => it.IsSelected).Select(it => it.Value));
cmd.Parameters.Add("@stIdCity", SqlDbType.NVarChar, 20).Value = value;
首先,我使用 LINQ 篩選選定的專案,然后獲取它們的值。string.Join用逗號組合結果值。
但請注意,您的存盤程序只接受一個nvarchar(20),因此在選擇多個城市時可能會耗盡空間。
uj5u.com熱心網友回復:
您只有一個引數,它是一個逗號分隔的值字串。
所以,你必須“建立”一個逗號分隔的字串。像這樣說:
string myparms = "";
foreach (ListItem item in lstBoxTestCity.Items)
{
if (item.Selected)
{
if (myparms != "")
myparms = ",";
myparms = item.Value;
}
}
cmd.Parameters.Add("@stIdCity",SqlDbType.NVarChar).Value = myparms;
因此,您只傳遞一個值 - 但您必須建立要傳遞的值的“字串”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/381697.html
標籤:C# 网站 sql-server
