日期:2014-05-17  浏览次数:20414 次

后台读取数据库,前台绑定到页面,出错了…………帮我看看吧
功能是想读取新闻内容。后台读取数据库,前台绑定到页面,出错了……

后台代码: 
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString());
  protected void Page_Load(object sender, EventArgs e)
  {
  if (Request.QueryString.ToString() != "")
  {
  string rqs = Request.QueryString["news_ID"];
  conn.Open();
  SqlCommand cmd = new SqlCommand();
  cmd.Connection = conn;
  cmd.CommandType = CommandType.Text;
  cmd.CommandText = "select [news_title] from [news] where [news_ID] =" + rqs;
  Page.DataBind();
  conn.Close();
  }
  else {
  Page.ClientScript.RegisterStartupScript(this.Parent.GetType(), "", "alert('请先选择新闻!');", true);
  }
  }


前台页面代码:
<div>新闻标题:<asp:TextBox ID="news_title" runat="server" Width="700px" Text='<%# DataBinder.Eval(Container.DataItem,"news_title") %>'></asp:TextBox></div>


错误提示:
“System.Web.UI.Control”不包含“DataItem”的定义,并且找不到可接受类型为“System.Web.UI.Control”的第一个参数的扩展方法“DataItem”(是否缺少 using 指令或程序集引用?)

------解决方案--------------------
再说了,就一个TextBox,获取单独的一个值,定义一个public变量即可

C# code

public string content = string.Empty; 
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString());
  protected void Page_Load(object sender, EventArgs e)
  {
       if (Request.QueryString.ToString() != "")
       {
           string rqs = Request.QueryString["news_ID"];
            conn.Open();
             string strSQL = "select [news_title] from [news] where [news_ID] =" + rqs;
            SqlDataAdapter adapter = new SqlDataAdapter(strSQL,con);
            DataSet ds = new DataSet();
            adapter.Fill(ds);
            content = ds.Tables[0].Rows[0]["news_title"].ToString();
             conn.Close();
        }
       else
       {
            Page.ClientScript.RegisterStartupScript(this.Parent.GetType(), "", "alert('请先选择新闻!');", true);
        }
  }

------解决方案--------------------
以前看视频的时候。上面的教我们用 DataBinder.Eval(Container.DataItem,可是看了别人写的项目代码全是EVal<%# "..."%>就过去了。。。。
小菜鸟、、、、、
------解决方案--------------------
你要用 数据绑定,你有绑定 控件没?
 例如 我用 Repeater 控件
C# code

<asp:Repeater id="repeater1" runat="server">
<ItemTemplate><div>新闻标题:<asp:TextBox ID="news_title" runat="server" Width="700px" Text='<%# Eval[color=#FF0000]("--这里用你数据库对应的列名--")%[/color]>'></asp:TextBox></div></ItemTemplate>
</asp:Repeater>

------解决方案--------------------
你连SQL语句都写错了"select [news_title] from [news] where [news_ID] =" + rqs;
应该是
C# code
"select [news_title] from [news] where [news_ID] =‘" + rqs + “’”;