不能隐式转换类型'& # 39;字符串# 39;在服务器端访问Div

本文关键字:字符串 服务器端 Div 访问 不能 转换 类型 | 更新日期: 2023-09-27 18:05:35

我要访问服务器端的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"

不能隐式转换类型'& # 39;字符串# 39;在服务器端访问Div

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

当您的查询只返回单个数据块时使用。在本例中,看起来您的查询只返回单行,其中只有Description列。如果这是正确的,那么您可以这样做:

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;
    }
}

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

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;
    }
}