如何动态填充SQL Server的列表框

时间:2014-03-23 11:37:32

标签: c#

我有一个具有以下结构的数据库。现在我想在c#中用这个表填充一个列表框。我怎么能这样做?

Column      | Type
------------------------------
ID          | Unique Identifier;
txtname     | nvarchar(50);
txtcitycode | nchar(5);

1 个答案:

答案 0 :(得分:1)

您可以使用此代码:

using (SqlConnection con = new SqlConnection(YOUR_CONNECTION_STRING))
        {
            using (SqlCommand cmd = new SqlCommand("Select ID, txtname, txtcitycode from YOUR_TABLE", con))
            {
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                DropDownList1.DataTextField = "txtname";
                DropDownList1.DataValueField = "txtcitycode";
                DropDownList1.DataSource = dt;
                DropDownList1.DataBind();
            }
        }

将“YOUR_CONNECTION_STRING”替换为连接字符串,将“YOUR_TABLE”替换为您的表名

如果你不知道连接字符串,你可以在这个网站上找到一些有用的信息:http://www.connectionstrings.com/