2012-08-23 293 views
0

我將數據庫中的值顯示在下拉列表中。但我無法獲得相應的值到DDL中。在下拉列表中顯示DB值

if (dt.Rows.Count > 0) 
      { 
       DataTable dt1 = new DataTable(); 
       dt1 = bll.getnewid(TextBox1.Text); 

        if (dt1.Rows.Count > 0) 
        { 

         Session["pid"] = dt1.Rows[0]["NewidColumn"].ToString(); 
         Session["email"] = dt1.Rows[0]["EmailID"].ToString(); 
         Session["gender"] = dt1.Rows[0]["Gender"].ToString(); 
         Session["mobile"] = dt1.Rows[0]["MobileNo"].ToString(); 
         Session["country"] = dt1.Rows[0]["Country"].ToString(); 
         Session["state"] = dt1.Rows[0]["State"].ToString(); 
         } 

,我顯示這樣

DropDownList1.Text = Session["country"].ToString(); 
      DropDownList2.Text = Session["state"].ToString(); 

我能夠得到DataTable中的國家和狀態值。但我無法在DDL中顯示它們。

回答

0

您需要設置您的下拉列表的SelectedValueSelectedIndex屬性。

1
DropDownList1.Items.Add(new ListItem(Session["country"].ToString()); 
DropDownList2.Items.Add(new ListItem(Session["state"].ToString()); 
+1

這裏有什麼選擇? –

+0

更新了答案。希望它有幫助 – Ashirvad

+0

參數'1':不能從'System.Web.UI.WebControls.ListItem'轉換爲'System.Web.UI.Control'\t 我得到這樣的錯誤。 –

1
DropDownList1.Items.Add(new ListItem(Session["country"].ToString()); 
DropDownList2.Items.Add(new ListItem(Session["state"].ToString()); 
Dropdownlist2.databind(); 
Dropdownlist1.databind(); 
+0

當我這樣做,我得到的價值,但在國家DDL它顯示 - 選擇一個國家,而不是國家名稱,如何直接顯示國家名稱。 –

+0

DropDownList2.Items.Add(new ListItem(Session [「ID」]。ToString(),Session [「countryname」]。ToString()); –

+0

這是什麼session [「ID」] ??我還沒有分配任何東西它可能對象引用沒有設置爲一個對象的實例錯誤將發生 –

0

嘗試這樣

DropDownList1.Items.Add("yourvalue"); 
    DropDownList1.Items.Add(Session["country"].ToString()); 
0

試試這個代碼:

DropDownList1.Items.Insert(0, new ListItem(Session["country"].ToString(), "0")); 
DropDownList1.DataBind(); 

DropDownList2.Items.Insert(0, new ListItem(Session["state"].ToString(), "0")); 
DropDownList2.DataBind(); 
0

什麼是使用會話的需要..? 而不是嘗試這個..hope它的作品。 經過這行代碼(dt1 = bll.getnewid(TextBox1.Text);) 使用這兩行代替會話。

DropDownList1.DataSource=dt1; 
DropDownList1.DataTextField="Country"; 
DropDownList1.DataValueField="Country"; 
DropDownList1.DataBind(); 
DropDownList2.DataSource=dt1; 
DropDownList2.DataValueField="Country"; 
DropDownList2.DataValueField="Country"; 
DropDownList2.DataBind(); 
+0

here country和狀態是數據表dt1中列的名稱,確保列名與dt1匹配 –

+0

我正在捕捉國家和州的值,並顯示在另一個頁面中,所以我正在使用會話。 –

+0

你是否打算說選定的國家和州或整個國家和州的名單..? –