从asp.net的mysql数据库获取信息

时间:2011-07-14 19:24:41

标签: c# asp.net mysql

我正在使用这些使用语句 -

  using System;
  using System.Data;
  using System.Data.Odbc;
  using System.Configuration;
  using System.Collections;
  using System.Web;
  using System.Web.Security;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.WebControls.WebParts;
  using System.Web.UI.HtmlControls;
  using System.Data.SqlClient;

这是我试图将术语信息放入下拉列表

   protected void getAppTerm()
         {
            string status, y;
           y = "";
            string CommandText = "select term from Terms";
            OdbcConnection myConnection = dbconnect();
            OdbcCommand myCommand = new OdbcCommand(CommandText, myConnection);

        try
        {
            myConnection.Open();
            OdbcDataReader reader = myCommand.ExecuteReader();
            while (reader.Read())
            {
                status = reader.GetString(0);
                foreach (ListItem item in ddlApplicationTerm.Items)
                {
                    y = item.Text;
                }
                if (!(status == y))
                {
                    ddlApplicationTerm.Items.Add(status);
                }
            }

        }
        catch (OdbcException ex)
        {

        }
        finally
        {
            myConnection.Close();
        }
    }

信息不会进入下拉列表。我也安装了所有驱动程序。

3 个答案:

答案 0 :(得分:2)

protected void getAppTerm()
{
    string CommandText = "select term from Terms";
    OdbcConnection myConnection = dbconnect();
    OdbcCommand myCommand = new OdbcCommand(CommandText, myConnection);

    try
    {
        myConnection.Open();
        OdbcDataReader reader = myCommand.ExecuteReader();
        while (reader.Read())
        {
            // Currently, you're overwriting the variable "y" on every iteration
            // and then just comparing the last item.text to status.

            var status = reader.GetString(0);
            if (!ddlApplicationTerm.Items.Contains(status)
                ddlApplicationTerm.Items.Add(status);
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.ToString());
    }
    finally
    {
        myConnection.Close();
    }
}

答案 1 :(得分:0)

如果您的数据位于SQL Server中,请尝试使用SqlConnection项。

SqlConnection myConn = new SqlConnection();
SQLCommand myCommand = new SQLCommand("Select term from Terms", myConn);
SqlDataReader myDR = myCommand.ExecuteReader;

答案 2 :(得分:0)

如果您尝试添加不在列表中的项目,则需要调整foreach循环中的代码:

foreach (ListItem item in ddlApplicationTerm.Items)
{
    if (!Status == item.Text)
    {
        ddlApplicationTerm.Items.Add(new ListItem(status));
    }
}