【问题标题】:Cannot implicitly convert type 'System.Data.DataSet' to 'string' access Div in Server Side无法在服务器端将类型“System.Data.DataSet”隐式转换为“字符串”访问 Div
【发布时间】:2014-07-16 11:37:15
【问题描述】:

我要在服务器端访问我的 div,然后我需要将数据绑定到该 div

我的代码:

 <div id="leftpanel" class="panel-body" runat="server">
                </div>

服务器端代码:

public void GetLeftPanelData()
{
    DataAccess da = new DataAccess();
    leftpanel.InnerText = da.GetLeftPanelData(); // <-- Error Shown here
}

数据存取方法

public DataSet GetLeftPanelData()
{
    try
    {
        SqlCommand comGetLeftPanelData = new SqlCommand("SP_GetLeftPanelData", con);
        comGetLeftPanelData.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(comGetLeftPanelData);
        DataSet ds = new DataSet();
        con.Open();
        da.Fill(ds);
        con.Close();
        return ds;
    }
    catch (Exception ee)
    {
        throw ee;
    }
}

我的存储过程

ALTER PROCEDURE [dbo].[SP_GetLeftPanelData]

AS
BEGIN
select Description 
from dbo.CommonPages
where Type= 6
END

这里返回编码的 HTML ![在此处输入图片描述][1]

在这个查询中只返回 1 行字符串,比如“Hello test data”

【问题讨论】:

  • 您有问题吗?错误很明显。
  • 如何解决这个问题?
  • 所以让我们考虑一下,通过将对象(string 的类型)的 InnerText 设置为 DataSet,您实际上希望它做什么做什么?
  • 我想获取数据并将 ti 放到左面板 div
  • @TechGuy:是的,有办法做到这一点。 GridView 就是其中一种方式。但我试图让你完成的是这个。如果我给你一篮苹果,让你做苹果派,你会把所有的苹果都扔进派盘吗?不,您必须翻译该输入 以获得所需的输出。 编程时请考虑这一点。您不能只将 div 的文本设置为某个输入并期望该输入正常工作。有意义吗?

标签: c# asp.net c#-4.0 data-access


【解决方案1】:

如果你必须使用这个方法(我建议不要),把你的方法改成这样:

public string GetLeftPanelData()
{
    try
    {
        SqlCommand comGetLeftPanelData = new SqlCommand("SP_GetLeftPanelData", con);
        comGetLeftPanelData.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(comGetLeftPanelData);
        DataSet ds = new DataSet();
        con.Open();
        da.Fill(ds);
        con.Close();
        return ds.Tables[0].Rows[0]["Description"].ToString();
    }
    catch (Exception ee)
    {
        throw ee;
    }
}

【讨论】:

    【解决方案2】:

    假设我在您更新的问题中看到的内容是正确的,我建议使用ExecuteScalar()

    当您的查询只返回一条数据时使用。在这种情况下,您的查询看起来只返回一行,只有列描述。如果这是正确的,你可以这样做:

    public string GetLeftPanelData()
    {
        try
        {
            SqlCommand comGetLeftPanelData = new SqlCommand("SP_GetLeftPanelData", con);
            comGetLeftPanelData.CommandType = CommandType.StoredProcedure;
            con.Open();
            string returnData = (string)comGetLeftPanelData.ExecuteScalar();
            con.Close();
            return returnData;
        }
        catch (Exception ee)
        {
            throw ee;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-17
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      相关资源
      最近更新 更多