2014-01-05 89 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()); 
} 
相關問題