想要将所有数据库从SQL Server绑定到dropdownlist(想要下拉列表中所有数据库的列表)

时间:2013-12-23 06:01:59

标签: c# sql-server

public partial class DropDownList : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            dropdownticket();
        }
    }

    string strsqlcon = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;

    protected void dropdownticket()
    {
        try
        {
            SqlConnection sqlconn = new SqlConnection(strsqlcon);
            SqlCommand cmd = new SqlCommand("SELECT * FROM SYS.databases", sqlconn);
            sqlconn.Open();
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataSet sd = new DataSet();
            sda.Fill(sd);
            Dropdownlist1.DataSource = sd;
            Dropdownlist1.DataTextField = "";
            Dropdownlist1.DataValueField = "";
            Dropdownlist1.DataBind();
            Dropdownlist1.Items.Insert(0, new ListItem("--Select--", "0"));
            sqlconn.Close();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
}

在上面的代码中,我无法在下拉列表中找到数据库列表。

2 个答案:

答案 0 :(得分:1)

您需要指定column来自DropDownList查询的SELECT <{1}}

name是从databsename查询中指定SELECT的列。

试试这个:

        Dropdownlist1.DataTextField = "name";
        Dropdownlist1.DataValueField = "name";

答案 1 :(得分:1)

您需要指定哪个列应从SELECT查询中分配给DropDownList,该列必须在Dropdownlist的DataTextField和DataValueField字段中添加。

   cmd.ExecuteNonQuery(); 
    Dropdownlist1.DataTextField = "name";
    Dropdownlist1.DataValueField = "name";