2012-09-06 97 views
1

即時通訊工作在一個asp.net網站與gridview。asp.net dropdownlist在gridview

gridview有來自sql數據庫的數據。

像:

Cuntry----Name 
USA--------John 
England----Frank 

...

數據在像這樣的GridView控件加載:

SqlCommand cmd; 
     cmd = new SqlCommand(); 
     cmd.Connection = sqlConn; 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.CommandText = "sp_loadData"; 
     sqlConn.Open(); 

     dr = cmd.ExecuteReader(); 

     DataTable dt = new DataTable(); 
     dt.Load(dr); 
     GridView1.DataSource = dt; 
     GridView1.DataBind(); 

所以,在名稱列,我希望有一個下拉列表。我希望下拉列表中的數據庫中的相應值被選中。

我該怎麼做?

由於

回答

1
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
    OnRowDataBound="GridView1_RowDataBound">  
    <Columns> 
    <asp:TemplateField HeaderText="Country"> 
    <ItemTemplate> 
     <asp:DropDownList Width="50" runat="server" id="ddlCountry" AutoPostBack="true"> 
     </asp:DropDownList> 
    </ItemTemplate> 
    </asp:TemplateField> 
</asp:GridView> 

代碼隱藏

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    //Checking whether the Row is Data Row 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     //Finding the Dropdown control. 
     Control ctrl = e.Row.FindControl("ddlCountry"); 
     if (ctrl != null) 
     { 
      DropDownList dd = ctrl as DropDownList; 
      //Here Bind with country list 
      dd.DataSource = lst; 
      //Put here the object properties name 
      dd.DataValueField = "idCountry"; 
      dd.DataTextField = "nameCountry"; 
      dd.DataBind(); 
      //Here add the code to select the current user country in the list 
      int idUserCountry = 10; 
      dd.Items.FindByValue(idUserCountry).Selected = true; 

     } 
    } 
} 
+0

IM這樣做: '代碼 CMD =新的SqlCommand(); cmd.Connection = sqlConn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText =「sp_Select」; sqlConn.Open(); dr = cmd.ExecuteReader(); DataTable dt = new DataTable(); dt.Load(dr); dd.DataSource = dt; dd.DataBind(); ' .... 但是當我執行,在下拉列表中,我得到的是:「System.Data.DataRowView」。沒有顯示實際值。 我該如何解決這個問題? – pyram

+0

你把這個代碼放在哪裏? – Massanu

+0

裏面的保護無效GridView1_RowDataBound(對象發件人,GridViewRowEventArgs e) – pyram