【问题标题】:Cannot implicitly convert type 'string' to 'System.Collections.Generic.List<string>无法将类型 'string' 隐式转换为 'System.Collections.Generic.List<string>
【发布时间】:2015-03-31 10:17:33
【问题描述】:

我的控制器显示错误请解决显示错误无法将列表转换为字符串

public JsonResult GetProperty_id(int selectedValue) 
{
    List < string > properties = new List < string > ().ToList();
    //    Property model1 = new Property();
    SqlConnection con = new SqlConnection("Server=miracle\\SQLExpress; database=CRUIdb; user id=sa; password=dotnet");
    con.Open();
    SqlCommand cmd = new SqlCommand("SELECT property_id  FROM Service_Property WHERE service_id =" + selectedValue, con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);

    for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++) 
    {
        properties = (ds.Tables[0].Rows[0]["property_id"]); //error cannot covert
    }
    return Json(properties, JsonRequestBehavior.AllowGet);
}

【问题讨论】:

标签: c#


【解决方案1】:

您将 string 值分配给 List&lt;string&gt; 这是不可能的,相反,您应该将每个值添加到您的集合中,如下所示

properties.Add(ds.Tables[0].Rows[0]["property_id"]);

【讨论】:

  • 另外,第一行不需要 ToList。列表属性=新列表().ToList();
【解决方案2】:

ds.Tables[0].Rows[0]["property_id"] 是 string,但您正在尝试将 properties 设置为该值。 properties 是其声明中的 List&lt;string&gt;。

也许你想做properties.Add(ds.Tables[0].Rows[0]["property_id"]),这与你在循环之后访问它的事实相匹配,即使它当前已编译,它也只会从最后一个循环中获取值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    相关资源
    最近更新 更多