将下拉列表绑定到数据库
问题描述:
我想将一个下拉列表绑定到一个数据库。我做了以下编码,但它不起作用。
I want to bind a dropdownlist to a database. I did the following coding but it isn't working.
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.Odbc;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rebind();
}
}
public void rebind()
{
try
{
OdbcConnection myConn = new OdbcConnection(ConfigurationManager.ConnectionStrings["myconn"].ConnectionString);
string sql = "select casename,casecode from casetype";
myConn.Open();
OdbcCommand cmd = new OdbcCommand(sql, myConn);
OdbcDataReader MyReader = cmd.ExecuteReader();
{
DropDownList3.DataSource= sql;
DropDownList3.DataTextField = "casename";
DropDownList3.DataValueField = "casetype";
DropDownList3.DataBind();
}
}
catch (Exception ex)
{
Response.Write(ex.StackTrace);
}
}
}
我是在c:\Documents和Settings\a\My Documents\\中的_Default.rebind()中将错误作为
I am getting the error as
at _Default.rebind() in c:\Documents and Settings\a\My Documents\Visual Studio 2008\WebSites\toolbar1\Default.aspx.cs:line 32
请帮助我解决我的问题,并将下拉列表绑定到数据源。我希望我的下拉列表从数据库列中显示文本,并在代码中稍后使用值字段进行其他目的。我在运行项目时显示页面,但无法在dropdownlist中获取数据
Please help me to solve my problem and bind the dropdownlist to a datasource.I want my dropdownlist to display text from a database column and use the value field for some other purpose later on in code. I am getting the page displayed when i run the project but not able to get the data in dropdownlist
答
您是否尝试使用DataAdapter这样吗?
Did you try using DataAdapter like this?
public void rebind()
{
try
{
OdbcConnection myConn = new OdbcConnection(ConfigurationManager.ConnectionStrings["myconn"].ConnectionString);
string sql = "select casename,casecode from casetype";
myConn.Open();
OdbcCommand cmd = new OdbcCommand(sql, myConn);
OdbcDataAdapter adapter = new OdbcDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
DropDownList3.DataSource = dt;
DropDownList3.DataTextField = "casename";
DropDownList3.DataValueField = "casecode";
DropDownList3.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.StackTrace);
}
}