2010-08-23 239 views
0

我有Repeater綁定方法此方法通過存儲過程從數據庫中檢索數據,當Model_Id傳遞給此方法時,它將檢索數據,當用戶多次選擇DDL時,用戶可以多次重複中繼器。我做的代碼,我添加哪些用戶從DDL在數組列表,但錯誤選擇所有Model_Ids出現無法將數組列表轉換爲字符串

不能數組列表轉換爲字符串值:

protected void Add_Click(object sender, ImageClickEventArgs e) 
{ 
    ArrayList Array = new ArrayList(); 
    Array.Add(DDLModel.SelectedValue); 
    DLHome.DataSource = Cls.GetModelName(Array); 
    DLHome.DataBind(); 
} 

public DataTable GetModelName(string Model_Id) 
{ 
    using (SqlConnection conn = Connection.GetConnection()) 
    { 
     SqlCommand cmd = new SqlCommand(); 
     cmd.Connection = conn; 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.CommandText = "GetComparisonModel"; 
     SqlParameter ParentID_Param = cmd.Parameters.Add("@Model_Id", SqlDbType.Int); 
     ParentID_Param.Value = Model_Id; 
     DataTable dt = new DataTable(); 
     SqlDataAdapter da = new SqlDataAdapter(); 
     da.SelectCommand = cmd; 
     da.Fill(dt); 
     return dt; 
    } 
} 

回答

0

當然,你得到一個編譯錯誤,如果這是你的確切代碼? GetModelName以字符串作爲參數,並且您傳入的類型爲ArrayList

如果你想將你的ID數組轉換爲字符串,只需要一個ArrayList的擴展方法,它迭代每個項並返回字符串值,例如在你的代碼

public static string ToArrayString(this ArrayList list) 
{ 
    return String.Join(", ", Cast<string>().ToArray()); 
} 

看,你可以簡單地傳遞SelectedValue直入綁定方法ArrayList使用出現n​​egligiable。

0

的錯誤是在這裏:

ArrayList Array = new ArrayList(); // Declare Array of type ArrayList 
Array.Add(DDLModel.SelectedValue); 
DLHome.DataSource = Cls.GetModelName(Array); // Pass Array to method that expects a string 

您正在嘗試將ArrayList傳入方法GetModelName。此方法需要一個string參數。

0

您的方法public DataTable GetModelName(string Model_Id)需要簽名中定義的字符串。

您正在嘗試一個ArrayList傳遞給方法 - Cls.GetModelName(Array);

你應該在IDE中得到警告這(和有關名爲Array變量)

1

除了其他人對於ArrayList和方法簽名中的字符串之間的數據類型不匹配的看法之外,您看起來並不像實際上希望它是字符串,因爲您將它作爲int參數傳遞給存儲過程。

我建議在第一種方法中,你想要做一個int.Parse(或int.TryParse,如你所見),並將其作爲int傳遞給方法。

0

順便說一句,你的代碼看起來是這樣的:

using (SqlConnection conn = Connection.GetConnection()) 
using (SqlCommand cmd = conn.CreateCommand()) 
{ 
    cmd.CommandType = CommandType.StoredProcedure; 
    cmd.CommandText = "GetComparisonModel"; 
    cmd.Parameters.Add("@Model_Id", SqlDbType.Int).Value = Model_Id; 
    DataTable dt = new DataTable(); 
    using (SqlDataAdapter da = new SqlDataAdapter(cmd)) 
    { 
     da.Fill(dt); 
    } 
    return dt; 
}