2014-01-05 92 views
0

我需要下拉的第一行代码是空的,下面是当前的代码我使用下拉列表第一行作为空

string queryString = "select College_Name from Colleges"; 
string constring = System.Configuration.ConfigurationManager 
         .ConnectionStrings["ConnDBForum"].ConnectionString; 
SqlConnection connection = new SqlConnection(constring); 
SqlCommand command = new SqlCommand(queryString, connection); 
connection.Open(); 
DataTable dt = new DataTable(); 
SqlDataAdapter ad = new SqlDataAdapter(command); 
ad.Fill(dt); 
if (dt.Rows.Count > 0) 
{ 
    DropDownList2.Items.Insert(0, new ListItem(String.Empty, String.Empty)); 
    DropDownList2.DataSource = dt; 
    DropDownList2.DataTextField = "College_Name"; 
    DropDownList2.DataValueField = "College_Name"; 
    DropDownList2.DataBind(); 
} 
connection.Close(); 

任何一个可以请帮我在这?

+0

将'Items.Insert'移动到'DataBind()'调用之后。 – Travis

+0

特拉维斯是对的。你可以使用'.Add()'方法而不是'.Insert()',因为在你检查是否包含任何内容之前,有两行。 – Andy

+0

请阅读文档。 – naveen

回答

1

在绑定之后移动插入,或者您可以使用dt.Rows.InsertAt将空行添加到数据表,那么您将不需要0​​。

DropDownList2.DataSource = dt; 
DropDownList2.DataTextField = "College_Name"; 
DropDownList2.DataValueField = "College_Name"; 
DropDownList2.DataBind(); 
DropDownList2.Items.Insert(0, new ListItem(String.Empty, String.Empty)); 
+0

看到我上面的评论。你可以改变它为“添加”?只是为了提供明确的代码 – Andy

+0

您不能使用Add来插入第0个索引。 –

+0

啊,是的,当然,你是对的。在最后一行没有用'Insert'重新考虑它。对于那个很抱歉。 – Andy

0

你可以使用一个foreach循环每个项目添加到下拉列表中,如果它是第一个项目,添加一个空白。

bool firstItem = true; 
foreach (DataRow row in dt.Rows) 
{ 
    if (firstItem) 
     comboBox1.Items.Add(""); 

    firstItem = false; 

    comboBox1.Items.Add(row[0].ToString()); 
} 
相关问题